Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence frombeginWord 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
.
思路1:一个map,一个队列,将每次转换的string加入到队列,并put到map中,距离+1,具体转换的方法网上其实有很多了,一般都是用将字符串的每一项分别用26个字母替换,并检查新的字符串是否在字典中,若是则添加到队列中,如果转换后得到endword,则返回距离,代码:
public int ladderLength(String beginWord, String endWord, Set<String> wordList) { Map<String,Integer> map=new HashMap<>(); map.put(beginWord,1); Queue<String> queue=new LinkedList<>(); queue.offer(beginWord); while(!queue.isEmpty()){ String temp=queue.poll(); int dis=map.get(temp); for(int i=0;i<temp.length();i++){ for(char j='a';j<='z';j++){ if(temp.charAt(i)==j) continue; StringBuffer str=new StringBuffer(temp); str.setCharAt(i,j); String trans=str.toString(); if(trans.equals(endWord)) return dis+1; if(wordList.contains(trans)&&!map.containsKey(trans)){ queue.offer(trans); map.put(trans,dis+1); } } } } return 0; }这个方法实际run时有时会超时,有时会通过,非常神奇,说明运行时间处于允许范围的边缘。
思路2:用双集合法,这个方法是上面思路的一种改进,代码写的非常巧妙,极大缩减允许时间,直接上代码吧,只能膜拜,出处leetcode discuss:
public int ladderLength(String beginWord, String endWord, Set<String> wordList) { Set<String> beginSet = new HashSet<String>(), endSet = new HashSet<String>(); int len = 1; int strLen = beginWord.length(); HashSet<String> visited = new HashSet<String>(); beginSet.add(beginWord); endSet.add(endWord); while (!beginSet.isEmpty() && !endSet.isEmpty()) { if (beginSet.size() > endSet.size()) { Set<String> set = beginSet; beginSet = endSet; endSet = set; } Set<String> temp = new HashSet<String>(); for (String word : beginSet) { char[] chs = word.toCharArray(); for (int i = 0; i < chs.length; i++) { for (char c = 'a'; c <= 'z'; c++) { char old = chs[i]; chs[i] = c; String target = String.valueOf(chs); if (endSet.contains(target)) { return len + 1; } if (!visited.contains(target) && wordList.contains(target)) { temp.add(target); visited.add(target); } chs[i] = old; } } } beginSet = temp; len++; } return 0; }