leetcode word ladder
先上题目
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog"
,
return its length 5
.o
最先考虑用动态规划,思路很简单,但是对于动态规划来说,最大的问题就是需要给出任意两个词是否相邻。这需要耗费
大量的时间,果然TLE了
然后考虑用迭代的方法,既然从beginWord出发,每次只能走一步,只能改变它的一个字母,那么我们可以
考虑所有可能的路径。
以上面的例子为例给出迭代过程
1.hit
2.hot
3.lot,dot
4.log,dog
5.cog
然而依然超时,上网找答案,发现答案的思路与我上面的思路是一致的,只是有一个实现不同,由hit生成hot的实现
我的实现是用hit去遍历整个Set,将hit与Set中的每一个单词进行比较,找距离为1的单词。
然而答案中的实现是,生成以距离hit为1的每一个可能的单词,如hat,hbt,hct.....,再用Set.contains方法去判断
Set中是否有这个单词。
另外,学到了一个nice的替换String中某个位置字符的方法
private String Replace(String s, int index, char c) { char[] chars = s.toCharArray(); chars[index] = c; return new String(chars); }
亲测这个方法效率极高。
下面给出代码
public class Solution5 { public int ladderLength(String start, String end, Set<String> dict) { if (dict == null) { return 0; } if (start.equals(end)) { return 1; } dict.add(start); dict.add(end); HashSet<String> hash = new HashSet<String>(); Queue<String> queue = new LinkedList<String>(); queue.offer(start); hash.add(start); int length = 1; while(!queue.isEmpty()) { System.out.println("hash:"+hash); System.out.println("queue"+queue); System.out.println("-----"); length++; int size = queue.size(); for (int i = 0; i < size; i++) { String word = queue.poll(); for (String nextWord: getNextWords(word, dict)) { if (hash.contains(nextWord)) { continue; } if (nextWord.equals(end)) { return length; } hash.add(nextWord); queue.offer(nextWord); } } } return 0; } // replace character of a string at given index to a given character // return a new string private String replace(String s, int index, char c) { char[] chars = s.toCharArray(); chars[index] = c; return new String(chars); } // get connections with given word. // for example, given word = 'hot', dict = {'hot', 'hit', 'hog'} // it will return ['hit', 'hog'] private ArrayList<String> getNextWords(String word, Set<String> dict) { ArrayList<String> nextWords = new ArrayList<String>(); for (char c = 'a'; c <= 'z'; c++) { for (int i = 0; i < word.length(); i++) { if (c == word.charAt(i)) { continue; } String nextWord = replace(word, i, c); if (dict.contains(nextWord)) { nextWords.add(nextWord); } } } return nextWords; }