[leetcode]Word Ladder @ Python


原題地址:https://oj.leetcode.com/problems/word-ladder/

題意:

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

For example,

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

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.

解題思路:這道題使用bfs來解決。參考:http://chaoren.is-programmer.com/posts/43039.html 使用BFS, 單詞和length一塊記錄, dict中每個單詞只能用一次, 所以用過即刪。dict給的是set類型, 檢查一個單詞在不在其中(word in dict)為O(1)時間。設單詞長度為L, dict里有N個單詞, 每次掃一遍dict判斷每個單詞是否與當前單詞只差一個字母的時間復雜度是O(N*L), 而每次變換當前單詞的一個字母, 看變換出的詞是否在dict中的時間復雜度是O(26*L), 所以要選擇后者。

代碼:

class Solution:
    # @param start, a string
    # @param end, a string
    # @param dict, a set of string!!!dict is a set type!!!
    # @return an integer
    def ladderLength(self, start, end, dict):
        dict.add(end)
        q = []
        q.append((start, 1))
        while q:
            curr = q.pop(0)
            currword = curr[0]; currlen = curr[1]
            if currword == end: return currlen
            for i in range(len(start)):
                part1 = currword[:i]; part2 = currword[i+1:]
                for j in 'abcdefghijklmnopqrstuvwxyz':
                    if currword[i] != j:
                        nextword = part1 + j + part2
                        if nextword in dict:
                            q.append((nextword, currlen+1)); 
                            dict.remove(nextword)
        return 0

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM