词典中最长的单词
给出一个字符串数组 words 组成的一本英语词典。返回 words 中最长的一个单词,该单词是由 words 词典中其他单词逐步添加一个字母组成。
若其中有多个可行的答案,则返回答案中字典序最小的单词。若无答案,则返回空字符串。
原文链接:
https://leetcode-cn.com/problems/longest-word-in-dictionary/
解题思路
涉及到前缀,便考虑使用字典树结构用于存储相同前缀的内容,当然本题也可以用hash表进行存储
遍历每个字符串,若前缀存在于字典树:
- 存储最大的
- 存储字典序最大的
实现代码
class Solution:
def longestWord(self, words: List[str]) -> str:
t = Trie() #不重复字典树的结构存储
for word in words:t.insert(word)
longest = ""
for word in words:
if t.search(word):
if(len(word) > len(longest) or (len(word) == len(longest) and word < longest)):
longest = word
return longest
细节:
python字符串比较
逐位比较每一位字符的ASCII码的大小,无关字符串长度
’b’>‘aaaa’ 为True