class Solution {
public int ladderLength(String beginWord
, String endWord
, List
<String> wordList
) {
Set
<String> dict
= new HashSet<>(wordList
);
if(! dict
.contains(endWord
)) return 0;
Queue
<String> queue
= new LinkedList<>();
queue
.add(beginWord
);
int step
= 0;
while(!queue
.isEmpty()){
int size
= queue
.size();
step
++;
while(size
-- >0){
String s
=queue
.poll();
char[] cur
= s
.toCharArray();
for(int i
=0;i
<cur
.length
;i
++){
char c
=cur
[i
];
for (char j
= 'a'; j
<= 'z'; j
++) {
cur
[i
] = j
;
String tp
= String
.valueOf(cur
);
if(endWord
.equals(tp
)) return step
+1;
if(! dict
.contains(tp
)) continue;
dict
.remove(tp
);
queue
.add(tp
);
}
cur
[i
]=c
;
}
}
}
return 0;
}
}
转载请注明原文地址: https://mac.8miu.com/read-504697.html