码迷,mamicode.com
首页 > 其他好文 > 详细

127. Word Ladder

时间:2016-06-15 08:02:10      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

相当于bfs

 1     public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
 2         if(beginWord == null || endWord == null || beginWord.length() == 0 || endWord.length() != beginWord.length() || wordList == null) {
 3             return 0;
 4         }
 5         Set<String> visited = new HashSet<String>();
 6         visited.add(beginWord);
 7         wordList.add(endWord);
 8         int length = 1;
 9         while(!visited.contains(endWord)) {
10             length++;
11             Set<String> currentWord = new HashSet<String>();
12             for(String word: visited) {
13                 for(int i = 0; i < word.length(); i++) {
14                     for(char j = ‘a‘; j <= ‘z‘; j++) {
15                         char[] wordArr = word.toCharArray();
16                         wordArr[i] = j;
17                         String curWord = new String(wordArr);
18                         if(!curWord.equals(word) && wordList.contains(curWord)) {
19                             currentWord.add(curWord);
20                             wordList.remove(curWord);
21                         }
22                     }
23                 }
24             }
25             if(currentWord.isEmpty()) {
26                 return 0;
27             }
28             visited  = currentWord;
29         }
30         return length;
31     }

 

127. Word Ladder

标签:

原文地址:http://www.cnblogs.com/warmland/p/5586132.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!