记录每一个单词的前缀,看前缀是否在集合中,如果前缀都在集合中,则添加单词,最后求最长的最小单词。
class Solution(object):
def longestWord(self, words):
ans = []
wordset = set(words)
for word in words:
flag = 1
for i in range(1,len(word)):
if word[:i] not in wordset:
flag = 0
if flag == 1:
ans.append(word)
if ans == []:
return ""
ans.sort(key=lambda x:[len(x), x],reverse=True)
l = len(ans[0])
res = ans[0]
for i in range(len(ans)):
if len(ans[i]) == l:
if res > ans[i]:
res = ans[i]
else:
break
return res
前缀树
from collections import defaultdict
class TrieNode:
def __init__(self):
self.children = defaultdict(TrieNode)
self.word = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
cur = self.root
for w in word:
cur = cur.children[w]
cur.word = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
cur = self.root
for w in word:
if w not in cur.children:
return False
cur = cur.children[w]
if cur.word:
return True
return False
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
cur = self.root
for p in prefix:
if p not in cur.children:
return False
cur = cur.children[p]
return True
720用前缀树解法,注意这里的需要判断前缀是否存在,搜索的时候每个词已经存在,所以直接判断当前词是否是结尾的词。
from collections import defaultdict
class TrieNode:
def __init__(self):
self.children = defaultdict(TrieNode)
self.word = False
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
cur = self.root
for w in word:
cur = cur.children[w]
cur.word = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
cur = self.root
for w in word:
cur = cur.children[w]
if not cur.word :
return False
if cur.word:
return True
return False
class Solution:
def longestWord(self, words: List[str]) -> str:
res=''
trie=Trie()
for word in words:
trie.insert(word)
for word in words:
if trie.search(word):
if len(word) > len(res):
res=word
elif len(word)==len(res) and word < res:
res=word
return res