127. 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:

  1. Only one letter can be changed at a time.
  2. Each transformed word must exist in the word list. Note that beginWord is not 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.

一刷
题解:BFS
构建set,首先将step全部为1的word加入set, 然后2, 3, ...直到有word为end
然后,为了节约时间,我们用two end, 这就意味着有一个begin set, 一个end set, 当begin set的size大于end set时,我们就从endSet开始找。
plus,为了避免重复的寻找,我们用一个visited set, 如果已经visited过, 就不考虑。

public class Solution {
    public int ladderLength(String beginWord, String endWord, List dict) {
        Set wordList = new HashSet<>(dict);
        Set beginSet = new HashSet(), endSet = new HashSet();

        int len = 1;
        int strLen = beginWord.length();
        HashSet visited = new HashSet();
        
        beginSet.add(beginWord);
        endSet.add(endWord);
        while (!beginSet.isEmpty() && !endSet.isEmpty()) {
            if (beginSet.size() > endSet.size()) {
                Set set = beginSet;
                beginSet = endSet;
                endSet = set;
            }

            Set temp = new HashSet();
            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;
    }
}

你可能感兴趣的:(127. Word Ladder)