-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path127. Word Ladder.java
43 lines (38 loc) · 1.22 KB
/
127. Word Ladder.java
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
43
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
LinkedList<String> q = new LinkedList<>();
q.add(beginWord);
HashSet<String> set = new HashSet<>(wordList);
if(!set.contains(endWord))
return 0;
int level = 0;
while(q.size() > 0)
{
level++;
if(q.contains(endWord))
{
return level;
}
int size = q.size();
while(size-- > 0)
{
String curr = q.removeFirst();
StringBuilder sb = new StringBuilder(curr);
for(int i = 0; i < curr.length(); i++)
{
for(char ch = 'a'; ch <= 'z'; ch++)
{
sb.setCharAt(i, ch);
if(set.contains(sb.toString()))
{
q.add(sb.toString());
set.remove(sb.toString());
}
}
sb.setCharAt(i, curr.charAt(i));
}
}
}
return 0;
}
}