https://leetcode.cn/problems/word-ladder/description/?envType=study-plan-v2&envId=top-interview-150
思路:这题好像和上一题 433. 最小基因变化 基本一样,都是通过bfs找最短路径。
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
boolean exist = false;
for(String s : wordList) {
if(s.equals(endWord)) {
exist = true;
break;
}
}
if(!exist) return 0;
// 存储字符串s与endWord的最短路径
HashMap<String, Integer> map = new HashMap<>();
map.put(endWord, 0);
map.put(beginWord, -1); // -1代表还没找到最短路径
Queue<String> queue = new LinkedList<>();
Queue<String> temp = new LinkedList<>();
queue.add(endWord);
int cnt = 1;
while(!queue.isEmpty()) {
cnt++;
while(!queue.isEmpty()) {
String s = queue.poll();
// 初始状态能否走到s状态
if(differ(beginWord, s) == 1) {
return cnt;
}
for(String str : wordList) {
if(!map.containsKey(str) && differ(str, s) == 1) {
temp.add(str);
map.put(str, cnt);
}
}
}
queue = temp;
temp = new LinkedList<>();
}
return 0;
}
/**
* 计算两个字符串之间的差异
* @param s 被计算串
* @param target 目标串
* @return 差异的字符数
*/
public int differ(String s, String target) {
int cnt = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != target.charAt(i)) {
cnt++;
}
}
return cnt;
}
}
433

被折叠的 条评论
为什么被折叠?



