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 }

 

posted @ 2016-02-16 09:33  一切不期而至  阅读(324)  评论(0编辑  收藏  举报