Word Ladder

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Word Ladder相关的知识,希望对你有一定的参考价值。

 1 public class Solution {
 2     public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
 3         if(!isValidParam(beginWord, endWord, wordList)) {
 4             return 0;
 5         } else if(beginWord.equals(endWord)) {
 6             return 1;
 7         }
 8         
 9         Set<String> visited = new HashSet<>();
10         LinkedList<String> currLevel = new LinkedList<>();
11         LinkedList<String> nextLevel = new LinkedList<>();
12         int cnt = 1;
13         currLevel.offer(beginWord);
14         visited.add(beginWord);
15         
16         while(currLevel.size() > 0) {
17             for(String word: currLevel) {
18                 StringBuilder buff = new StringBuilder(word);
19                 for(int i = 0; i < buff.length(); i++) {
20                     char currChar = buff.charAt(i);
21                     for(char c = ‘a‘; c <= ‘z‘; c++) {
22                         buff.setCharAt(i, c);
23                         String tmpWord = buff.toString();
24                         
25                         // found the endWord
26                         if(endWord.equals(tmpWord)) {
27                             return cnt + 1;
28                         }
29                         
30                         if(visited.contains(tmpWord) || !wordList.contains(tmpWord)) {
31                             continue;
32                         } else {
33                             visited.add(tmpWord);
34                             nextLevel.add(tmpWord);
35                         }
36                     }
37                     buff.setCharAt(i, currChar);
38                 }
39             }
40             currLevel = nextLevel;
41             nextLevel = new LinkedList<String>();
42             cnt++;
43         }
44         
45         return 0;
46     }
47     
48     private boolean isValidParam(String beginWord, String endWord, Set<String> dict) {
49         boolean isValid = true;
50         if(beginWord == null || endWord == null || beginWord.length() != endWord.length()) {
51             isValid = false;
52         }
53         if(dict == null || dict.size() == 0) {
54             isValid = false;
55         }
56         return isValid;
57     }
58 }

 

以上是关于Word Ladder的主要内容,如果未能解决你的问题,请参考以下文章

Word Ladder

127. Word Ladder

126. Word Ladder II

Word Ladder系列

Word Ladder

[LeetCode] 127 Word Ladder