剑指 Offer II 108. 单词演变
思路: 每次都找下一层符合规则的单词。
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Deque<String> queue = new LinkedList<>();
queue.offer(beginWord);
int count = 1;
//存储已经遍历过的词
List<String> dumplicate = new ArrayList<>();
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
String word = queue.poll();
//存储遍历了几层,找到几层说明有几个词。
count++;
List<String> nexts = getNext(word, wordList);
if (nexts.size() == 0) {
return -1;
}
for (String next : nexts) {
if (dumplicate.contains(next)) {
continue;
}
if (next.equals(endWord)) {
return count;
}
dumplicate.add(next);
queue.offer(next);
}
}
}
return -1;
}
private List<String> getNext(String word, List<String> wordList) {
List<String> list = new ArrayList<>();
for (char i = 'a'; i < 'z'; i++) {
for (int j = 0; j < word.length(); j++) {
String pNext = changeWord(word, i, j);
if (wordList.contains(pNext)) {
list.add(pNext);
}
}
}
return list;
}
private String changeWord(String word, char i, int j) {
char[] words = word.toCharArray();
words[j] = i;
return new String(words);
}