0127. Word Ladder (H)

Word Ladder (H)

题目

Given two words beginWord and endWord, and a dictionary wordList, return the length of the shortest transformation sequence from beginWord to endWord, such that:

  • Only one letter can be changed at a time.
  • Each transformed word must exist in the word list.

Return 0 if there is no such transformation sequence.

Example 1:

Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", return its length 5.

Example 2:

Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
Output: 0
Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.

Constraints:

  • 1 <= beginWord.length <= 100
  • endWord.length == beginWord.length
  • 1 <= wordList.length <= 5000
  • wordList[i].length == beginWord.length
  • beginWord, endWord, and wordList[i] consist of lowercase English letters.
  • beginWord != endWord
  • All the strings in wordList are unique.

题意

给定一个初始字符串、目标字符串、一组字符串序列,从初始字符串开始,每次改变其中一个字符,使得到的新字符串是序列中的一个,重复操作,判断最终能否得到目标字符串。

思路

BFS。从初始字符串开始,变动其中的每一个字符,将其改为另外25个字母,判断得到的新字符串是否在序列中,如果在的话加入队中,重复操作直到找到目标字符串。


代码实现

Java

class Solution {
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        Set<String> set = new HashSet<>();
        Queue<String> q = new LinkedList<>();
        int step = 0;

        for (String word : wordList) {
            set.add(word);
        }
        q.offer(beginWord);

        while (!q.isEmpty()) {
            step++;
            int size = q.size();
            for (int i = 0; i < size; i++) {
                String cur = q.poll();
                for (int index = 0; index < cur.length(); index++) {
                    char c = cur.charAt(index);
                    String before = cur.substring(0, index);
                    String after = cur.substring(index + 1, cur.length());
                    for (int j = 0; j < 26; j++) {
                        if (j != c - 'a') {
                            String newWord = before + (char) ('a' + j) + after;
                            if (set.contains(newWord)) {
                                if (endWord.equals(newWord)) {
                                    return step + 1;
                                }
                                q.offer(newWord);
                                set.remove(newWord);
                            }
                        }
                    }
                }
            }
        }

        return 0;
    }
}
原文地址:https://www.cnblogs.com/mapoos/p/14256677.html