美文网首页
2019-10-17

2019-10-17

作者: Mree111 | 来源:发表于2019-10-18 03:54 被阅读0次

    Description

    给出两个单词(start和end)和一个字典,找出从start到end的最短转换序列,输出最短序列的长度。

    变换规则如下:

    每次只能改变一个字母。
    变换过程中的中间单词必须在字典中出现。(起始单词和结束单词不需要出现在字典中)

    Solution

    使用BFS O(M×N)

    class Solution:
        """
        @param: start: a string
        @param: end: a string
        @param: dict: a set of string
        @return: An integer
        """
        def ladderLength(self, start, end, dict):
            dict.add(end)
            queue = collections.deque([start])
            visited = set([start])
            
            distance = 0
            while queue:
                distance += 1
                for i in range(len(queue)):
                    word = queue.popleft()
                    if word == end:
                        return distance
                    
                    for next_word in self.get_next_words(word):
                        if next_word not in dict or next_word in visited:
                            continue
                        queue.append(next_word)
                        visited.add(next_word) 
    
            return 0
            
        # O(26 * L^2)
        # L is the length of word
        def get_next_words(self, word):
            words = []
            for i in range(len(word)):
                left, right = word[:i], word[i + 1:]
                for char in 'abcdefghijklmnopqrstuvwxyz':
                    if word[i] == char:
                        continue
                    words.append(left + char + right)
            return words
    

    相关文章

      网友评论

          本文标题:2019-10-17

          本文链接:https://www.haomeiwen.com/subject/rhvbmctx.html