转载地址:https://blog.csdn.net/mine_song/article/details/68951974
127. Word Ladder
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence frombeginWord toendWord, such that:
- Only one letter can be changed at a time.
- Each transformed word must exist in the word list. Note thatbeginWord isnot a transformed word.
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog"
,
return its length 5
.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
- You may assume no duplicates in the word list.
- You may assume beginWord and endWord are non-empty and are not the same.
UPDATE (2017/1/20):
The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
给出两个单词(start和end)和一个字典,找到从start到end的最短转换序列
比如:
- 每次只能改变一个字母。
- 变换过程中的中间单词必须在字典中出现。
- import java.util.*;
- public class word {
- public int ladderLength(String beginWord, String endWord, List<String> wordList) {
- if (beginWord == null || endWord == null || beginWord.length() == 0 || endWord.length() == 0
- || beginWord.length() != endWord.length())
- return 0;
- // 此题关键是去重,还有去除和beginWord,相同的单词
- Set<String> set = new HashSet<String>(wordList);
- if (set.contains(beginWord))
- set.remove(beginWord);
- Queue<String> wordQueue = new LinkedList<String>();
- int level = 1; // the start string already count for 1
- int curnum = 1;// the candidate num on current level
- int nextnum = 0;// counter for next level
- // 或者使用map记录层数
- // Map<String, Integer> map = new HashMap<String, Integer>();
- // map.put(beginWord, 1);
- wordQueue.add(beginWord);
- while (!wordQueue.isEmpty()) {
- String word = wordQueue.poll();
- curnum--;
- // int curLevel = map.get(word);
- for (int i = 0; i < word.length(); i++) {
- char[] wordunit = word.toCharArray();
- for (char j = 'a'; j <= 'z'; j++) {
- wordunit[i] = j;
- String temp = new String(wordunit);
- if (set.contains(temp)) {
- if (temp.equals(endWord))
- // return curLevel + 1;
- return level + 1;
- // map.put(temp, curLevel + 1);
- nextnum++;
- wordQueue.add(temp);
- set.remove(temp);
- }
- }
- }
- if (curnum == 0) {
- curnum = nextnum;
- nextnum = 0;
- level++;
- }
- }
- return 0;
- }
- }