标签:
给定一个起始字符串和一个目标字符串,现在将起始字符串按照特定的变换规则转换为目标字符串,求最少要进行多少次转换。转换规则为每次只能改变字符串中的一个字符,且每次转换后的字符串都要在给定的字符串集合中。
注意点:
例子:
输入: beginWord = “hit”, endWord = “cog”, wordList = [“hot”,”dot”,”dog”,”lot”,”log”]
输出: 5 (“hit” -> “hot” -> “dot” -> “dog” -> “cog”)
因为每次变换后的字符串都要在给定的字符串组中,所以每次变化的情况都是有限的。现在把变化过程做成一个树的结构,由某一个字符串变化而来的字符串就成为该字符串的子树。参看下图的例子,我们可以得到以下几点结论:
注:图中的有些单词没有意义,只是单纯为了举例子,图对应的起始字符串为hit,给定的字符串集合为{“hot”,”hat”,”bit”,”him”,”bot”,”bim”}
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: Set[str]
:rtype: int
"""
wordList.add(endWord)
cur_level = [beginWord]
next_level = []
depth = 1
n = len(beginWord)
while cur_level:
for item in cur_level:
if item == endWord:
return depth
for i in range(n):
for c in ‘abcdefghijklmnopqrstuvwxyz‘:
word = item[:i] + c + item[i + 1:]
if word in wordList:
wordList.remove(word)
next_level.append(word)
depth += 1
cur_level = next_level
next_level = []
return 0
if __name__ == "__main__":
assert Solution().ladderLength("hit", "cog", {"hot", "dot", "dog", "lot", "log"}) == 5
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
标签:
原文地址:http://blog.csdn.net/u013291394/article/details/51326575