您的位置:首页 > 其它

127. Word Ladder

2016-06-15 07:49 197 查看
相当于bfs

public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
if(beginWord == null || endWord == null || beginWord.length() == 0 || endWord.length() != beginWord.length() || wordList == null) {
return 0;
}
Set<String> visited = new HashSet<String>();
visited.add(beginWord);
wordList.add(endWord);
int length = 1;
while(!visited.contains(endWord)) {
length++;
Set<String> currentWord = new HashSet<String>();
for(String word: visited) {
for(int i = 0; i < word.length(); i++) {
for(char j = 'a'; j <= 'z'; j++) {
char[] wordArr = word.toCharArray();
wordArr[i] = j;
String curWord = new String(wordArr);
if(!curWord.equals(word) && wordList.contains(curWord)) {
currentWord.add(curWord);
wordList.remove(curWord);
}
}
}
}
if(currentWord.isEmpty()) {
return 0;
}
visited  = currentWord;
}
return length;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: