|
1 | 1 | class Solution {
|
2 |
| - public int ladderLength(String startWord, String targetWord, List<String> wordList) { |
3 |
| - |
4 |
| - HashSet<String> st = new HashSet<>(); |
5 |
| - for(String str :wordList){ |
6 |
| - st.add(str); |
| 2 | + public int ladderLength(String beginWord, String endWord, List<String> wordList) { |
| 3 | + HashSet<String> set = new HashSet<>(); |
| 4 | + for(String word : wordList){ |
| 5 | + set.add(word); |
7 | 6 | }
|
| 7 | + |
8 | 8 | Queue<Pair> que = new LinkedList<>();
|
9 |
| - que.offer(new Pair(startWord,1)); |
10 |
| - st.remove(startWord); |
| 9 | + que.offer(new Pair(beginWord,1)); |
| 10 | + set.remove(beginWord); |
| 11 | + |
11 | 12 | while(!que.isEmpty()){
|
12 |
| - String word =que.peek().word; |
13 |
| - int dist =que.peek().dist; |
14 |
| - que.poll(); |
15 |
| - if(word.equals(targetWord) == true) return dist; |
| 13 | + Pair pp = que.poll(); |
| 14 | + String curr = pp.word; |
| 15 | + int dist = pp.dist; |
16 | 16 |
|
17 |
| - for(int i=0;i<word.length();i++){ |
| 17 | + if(curr.equals(endWord)){ |
| 18 | + return dist; |
| 19 | + } |
| 20 | + for(int i=0;i<curr.length();i++){ |
18 | 21 | for(char ch='a';ch<='z';ch++){
|
19 |
| - char replace[] =word.toCharArray(); |
| 22 | + char replace[] =curr.toCharArray(); |
20 | 23 | replace[i]=ch;
|
21 | 24 | String newreplaced =new String(replace);
|
22 |
| - if(st.contains(newreplaced)==true){ |
23 |
| - st.remove(newreplaced); |
| 25 | + if(set.contains(newreplaced)){ |
| 26 | + set.remove(newreplaced); |
24 | 27 | que.offer(new Pair(newreplaced,dist+1));
|
25 | 28 | }
|
26 | 29 | }
|
|
0 commit comments