給定字典中的兩個詞,長度相等。寫乙個方法,把乙個詞轉換成另乙個詞, 但是一次只能改變乙個字元。每一步得到的新詞都必須能在字典中找到。
編寫乙個程式,返回乙個可能的轉換序列。如有多個可能的轉換序列,你可以返回任何乙個。
示例 1:
輸入:beginword = "hit",
endword = "cog",
wordlist = ["hot","dot","dog","lot","log","cog"]
輸出:["hit","hot","dot","lot","log","cog"]
示例 2:
輸入:beginword = "hit"
endword = "cog"
wordlist = ["hot","dot","dog","lot","log"]
輸出:
解釋: endword "cog" 不在字典中,所以不存在符合要求的轉換序列。
一、bfs
class solution:
def findladders(self, beginword: str, endword: str, wordlist: list[str]) -> list[str]:
hashmap = collections.defaultdict(list)
for word in wordlist:
for i in range(len(word)):
helper1 = [beginword]
helper2 =
while helper1:
word = helper1.pop()
if word == endword:
return helper2[word]
for i in range(len(word)):
if word[:i] + '*' + word[i+1:] in hashmap:
for tmp in hashmap[word[:i] + '*' + word[i+1:]]:
if tmp not in helper2:
helper2[tmp] = helper2[word] + [tmp]
return
二、dfs
class solution:
def findladders(self, beginword: str, endword: str, wordlist: list[str]) -> list[str]:
dic = collections.defaultdict(set)
for word in wordlist:
for i in range(len(word)):
dic[word[:i] + '*' + word[i+1:]].add(word)
self.res =
def dfs(cur, temp, marked):
if cur == endword:
self.res = temp.copy()
return
for i in range(len(cur)):
for word in dic[cur[:i] + '*' + cur[i+1:]]:
if word not in marked:
marked.add(word)
dfs(word, temp+[word],marked)
dfs(beginword, , )
return [beginword] + self.res if self.res else self.res
Leetcode BFS 單詞轉換
給定兩個單詞 初始單詞和目標單詞 和乙個單詞字典,請找出所有的從初始單詞到目標單詞的最短轉換序列的長度 每一次轉換只能改變乙個單詞 每乙個中間詞都必須存在單詞字典當中 例如 給定的初始單詞start hit 目標單詞end cog 單詞字典dict hot dot dog lot log 乙個最短的...
C 單詞轉換例子
今天在看 c primer 的時候書上有一道例子,於是就自己實現了一遍。例子的名稱叫做單詞轉換,使用了map物件,難度並不大。實現思路 先把單詞都存到乙個檔案裡面,檔案名叫dictionary.txt。然後 如下 include include include include include usi...
c 單詞轉換函式
c primer上的乙個例子,輸入乙個轉換對映檔案和乙個待轉換檔案,輸出轉換後結果。用c 的map來實現。建立對映函式 map buildmap ifstream map file return trans map 轉換函式 const string transform const string s...