-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0127. Word Ladder
42 lines (40 loc) · 1.29 KB
/
0127. Word Ladder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
public boolean trans(String s1, String s2){
if(s1.length() != s2.length()) return false;
int sum = 0;
for(int i = 0; i < s1.length(); i++){
if(s1.charAt(i) != s2.charAt(i))
sum += 1;
if(sum == 2) return false;
}
return true;
}
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
int res = 1;
LinkedList<String> qu = new LinkedList<>();
qu.add(beginWord);
while(!qu.isEmpty()){
LinkedList<String> newQu = new LinkedList<>();
boolean flag = false;
while(!qu.isEmpty()){
String top = qu.poll();
if(top.equals(endWord))
return res;
for(int i = 0; i < wordList.size();){
if(trans(top, wordList.get(i))){
newQu.add(wordList.get(i));
wordList.remove(i);
flag = true;
}
else i++;
}
}
if(flag){
res += 1;
qu = newQu;
}
else return 0;
}
return 0;
}
}