-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLadderLength.java
More file actions
123 lines (113 loc) · 3.66 KB
/
Copy pathLadderLength.java
File metadata and controls
123 lines (113 loc) · 3.66 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package bfs;
import org.junit.Test;
import java.util.*;
public class LadderLength {
/**
* @param start: a string
* @param end: a string
* @param dict: a set of string
* @return: An integer
* <p>
* 120. 单词接龙
* 给出两个单词(start和end)和一个字典,找到从start到end的最短转换序列
* <p>
* 比如:
* <p>
* 1.每次只能改变一个字母。
* 2.变换过程中的中间单词必须在字典中出现。
* 样例
* 给出数据如下:
* <p>
* start = "hit"
* <p>
* end = "cog"
* <p>
* dict = ["hot","dot","dog","lot","log"]
* <p>
* 一个最短的变换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog",
* <p>
* 返回它的长度 5
* <p>
* 注意事项
* 如果没有转换序列则返回0。
* 所有单词具有相同的长度。
* 所有单词都只包含小写字母。
* <p>
* 求图的最短路径使用bfs
*/
public int ladderLength(String start, String end, Set<String> dict) {
// write your code here
if (dict == null) {
return 0;
}
if (start.equals(end)) {
return 1;
}
//hashSet用于过滤已经使用的dict中的元素,防止再走一遍
HashSet<String> hashSet = new HashSet<>();
//queue中放每一层的节点
LinkedList<String> linkedList = new LinkedList<>();
hashSet.add(start);
linkedList.add(start);
//可能dict中没有end,但是会有end的上一步的word
dict.add(end);
//下面开始遍历一层中所有的next,想象成一颗二叉树的层次遍历
int result = 1;
while (!linkedList.isEmpty()) {
//遍历的层数就是路径的长度
result++;
int layerSize = linkedList.size();
for (int i = 0; i < layerSize; i++) {
String poll = linkedList.poll();
for (String nextWord : getNextWords(poll,dict)) {
if (hashSet.contains(nextWord)) {
continue;
}
if (nextWord.equals(end)) {
return result;
}
hashSet.add(nextWord);
linkedList.add(nextWord);
}
}
}
return 0;
}
private String replace(String s, int index, char c) {
char[] chars = s.toCharArray();
chars[index] = c;
return new String(chars);
}
private ArrayList<String> getNextWords(String word, Set<String> dict) {
char[] chars = word.toCharArray();
ArrayList<String> nextWords = new ArrayList<>();
for (int j = 0; j < chars.length; j++) {
for (char i = 'a'; i <= 'z'; i++) {
if (chars[j] == i) {
continue;
}
String nextString = replace(word, j, i);
if (dict.contains(nextString)) {
nextWords.add(nextString);
}
}
}
return nextWords;
}
@Test
public void testGetNextWords() {
String word = "chen";
Set<String> dict = new HashSet<>();
dict.add("chea");
dict.add("cheb");
dict.add("chec");
dict.add("chan");
dict.add("chbn");
dict.add("chba");
dict.add("chca");
dict.add("cdca");
// ArrayList<String> nextWords = getNextWords(word, dict);
// System.out.println(Arrays.toString(nextWords.toArray()));
System.out.println(ladderLength(word,"cdca",dict));
}
}