【LeetCode】Word Ladder 字串
題目:Word Ladder
<span style="font-size:18px;">/**LeetCode word ladder
* 題目:給定一個起始單詞和一個終結單詞以及一個字典,要求每次變換一個字元,成為字典中新的詞,直到變為最後的詞,要求其最短路徑
* 思路:利用佇列,先彈出第一個詞,分別將詞中每一個字元替換直到找到一個字典中存在的詞,加入佇列,直到匹配的詞是最後一個,此時終止
* 如果沒有這樣的路徑,則返回0
*/
package javaTrain;
import java.util.LinkedList;
import java.util.Set;
public class Train21 {
public int ladderLength(String start, String end, Set<String> dict) {
if(dict.size() == 0) return 0;
LinkedList<String> queue = new LinkedList();
String tag = new String();
queue.add(start);
queue.add(tag);
int len = 1;
while(queue.size() > 1){
String top = queue.pop();
if(top == tag){ //標誌著對於一個詞的每個字元的替換測試已經結束,有用的都放在佇列後面了
len++;
queue.add(tag);
continue;
}
else if(top == end){
return len;
}
for(int i = 0;i < top.length();i++){
char[] zifu = top.toCharArray();
for(char c = 'a';c <= 'z';c++){
zifu[i] = c;
String newWord = new String(zifu);
if(dict.contains(newWord)){
queue.add(newWord);
}
dict.remove(newWord);
}
}
} </span>
<span style="font-size:18px; font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre"> </span>return 0;</span>
<span style="font-size:18px;"> }
}
</span>
相關文章
- Leetcode Word LadderLeetCode
- LeetCode-Word LadderLeetCode
- Word Ladder leetcode javaLeetCodeJava
- Leetcode-Word Ladder IILeetCode
- Word Ladder II leetcode javaLeetCodeJava
- LeetCode126:Word LadderLeetCode
- LeetCode127:Word Ladder IILeetCode
- Leetcode Word SearchLeetCode
- Leetcode Word BreakLeetCode
- Leetcode-Word SearchLeetCode
- LeetCode-Word PatternLeetCode
- LeetCode-Word BreakLeetCode
- Leetcode Length of Last WordLeetCodeAST
- Word Search leetcode javaLeetCodeJava
- Word Break leetcode javaLeetCodeJava
- [leetcode]length-of-last-wordLeetCodeAST
- [LeetCode] 425. Word SquaresLeetCode
- LeetCode-Unique Word AbbreviationLeetCode
- LeetCode-Word Pattern IILeetCode
- LeetCode139:Word BreakLeetCode
- Leetcode-Word Break IILeetCode
- 【leetcode】length of last word (easy)LeetCodeAST
- Leetcode-Length of Last WordLeetCodeAST
- Word Break II leetcode javaLeetCodeJava
- LeetCode-Shortest Word DistanceLeetCode
- LeetCode-Add and Search WordLeetCode
- LeetCode-Maximum Product of Word LengthsLeetCode
- 動態規劃——字串分割(Word Break)動態規劃字串
- [LeetCode] 212. Word Search IILeetCode
- [LeetCode] 243. Shortest Word DistanceLeetCode
- LeetCode-Shortest Word Distance IILeetCode
- LeetCode-Shortest Word Distance IIILeetCode
- LeetCode140:Word Break IILeetCode
- 【LeetCode】Word Break 動態規劃LeetCode動態規劃
- leetcode:字串相乘(java)LeetCode字串Java
- [LeetCode] 244. Shortest Word Distance IILeetCode
- 【LeetCode】Word Break II 動態規劃LeetCode動態規劃
- leetcode 87 擾亂字串LeetCode字串