补0915
答案:
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
boolean f = false;
for(String word:wordList){
if(word.equals(endWord)){
f=true;
break;
}
}
if(f==false)return 0;
Queue<String> queue = new LinkedList<>();
queue.add(beginWord);
int time=0;
while(queue.size()>0){
int len = queue.size();
time++;
for(int i=0;i<len;i++){
String curWord = queue.poll();
for(int j=0;j<wordList.size();j++){
String word = wordList.get(j);
if(isNext(curWord,word)==1){
if(word.equals(endWord))return time+1;
queue.add(word);
wordList.remove(j);
j--;
}
}
}
}
return 0;
}
private int isNext(String str1,String str2){
int num=0;
for(int i=0;i<str1.length();i++){
if(str1.charAt(i)!=str2.charAt(i)){
num++;
}
}
if(num>1){
return -1;
}else{
return 1;
}
}
}