你好,這是我的前綴特里代碼部分的所有的話,我試圖得到它的底部比只是前綴返回更多,更多的解釋:如何改變這種前綴特里返回包含類似前綴
class TrieNode:
def __init__(self):
self.isString = False
self.children = {}
def insertString(word, root):
currentNode = root
for char in word:
if char not in currentNode.children:
currentNode.children[char] = TrieNode()
currentNode = currentNode.children[char]
currentNode.isString = True
def findStrings(prefix, node, results):
if node.isString:
results.append(prefix)
for char in node.children:
findStrings(prefix + char, node.children[char], results)
def longestPrefix(word, root):
currentNode = root
currentPrefix = ''
for char in word:
if char not in currentNode.children:
break
else:
currentNode = currentNode.children[char]
currentPrefix += char
strings = []
findStrings(currentPrefix, currentNode, strings)
return strings
pass
# Discussion: Is it dangerous to assume that findStrings actually found a string?
# Hint: There is an edge case that will break this
wordList = ['aydt', 'coombs', 'schuhmacher', 'claypoole', 'exhume', 'forehands', 'carin', 'plaits', 'alfonsin',
'hometowns', 'pedestals', 'emad', 'hourly', 'purchaser', 'spogli', 'combativeness', 'henningsen', 'luedke',
'duchin', 'koglin', 'teason', 'bumpings', 'substantially', 'lamendola', 'cecola', 'henze', 'tutti', 'dills',
'satirical', 'jetted', 'intertwine', 'predict', 'breezes', 'cyclist', 'ancillary', 'schaumburg', 'viewer',
"bay's", 'emissions', 'kincheloe', 'trees', 'vipperman', 'exhale', 'ornamental', 'repeated', 'pedestal',
'pedesta', 'pedest']
root = TrieNode()
for word in wordList:
insertString(word, root)
allWords = []
findStrings('', root, allWords)
print(allWords)
inputWord = 'co'
print(longestPrefix(inputWord, root))
inputWord = 'pedestals'
print(longestPrefix(inputWord, root))
我想知道如何獲得print(longestPrefix('pedestals', root))
返回'基座','基座','pedesta','pedest',而不僅僅是基座。我在代碼中缺少什麼?
'in'似乎不正確 - 可能更好使用'startswith'。但是這不使用OP的trie結構,所以它只是這個問題的另一種解決方案。 – usr2564301