-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path127.java
77 lines (75 loc) · 2.67 KB
/
127.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> wordSet = new HashSet<>();
for(String word : wordList) wordSet.add(word);
Set<String> visited = new HashSet<>();
Queue<String> queue = new LinkedList<>();
queue.offer(beginWord);
visited.add(beginWord);
int level = 1;
while(!queue.isEmpty()){
int size = queue.size();
while(size-->0){
String word = queue.poll();
if(word.equals(endWord)) return level;
char[] wc = word.toCharArray();
for(int i=0;i<wc.length;i++){
char old = wc[i];
for(int j=0;j<26;j++){
wc[i] = (char)(j+'a');
String temp = new String(wc);
if(wordSet.contains(temp)&&!visited.contains(temp)){
visited.add(temp);
queue.offer(temp);
}
wc[i] = old;
}
}
}
level++;
}
return 0;
}
}
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> wordSet = new HashSet<>();
for(String word : wordList) wordSet.add(word);
if(!wordSet.contains(endWord)) return 0;
Set<String> visited = new HashSet<>();
Set<String> beginSet = new HashSet<>();
Set<String> endSet = new HashSet<>();
beginSet.add(beginWord);
endSet.add(endWord);
visited.add(beginWord);
int level = 1;
Set<String> temp;
while(!beginSet.isEmpty()&&!endSet.isEmpty()){
if(beginSet.size()>endSet.size()){
temp = beginSet;
beginSet = endSet;
endSet = temp;
}
temp = new HashSet<>();
for(String word : beginSet){
char[] wc = word.toCharArray();
for(int i=0;i<wc.length;i++){
char old = wc[i];
for(int j=0;j<26;j++){
wc[i] = (char)(j+'a');
String t = new String(wc);
if(endSet.contains(t)) return level+1;
if(wordSet.contains(t)&&!visited.contains(t)){
visited.add(t);
temp.add(t);
}
wc[i] = old;
}
}
}
level++;
beginSet = temp;
}
return 0;
}
}