LeetCode 720 詞典中最長的單詞

2021-10-01 06:28:57 字數 817 閱讀 2288

給出乙個字串陣列words組成的一本英語詞典。從中找出最長的乙個單詞,該單詞是由words詞典中其他單詞逐步新增乙個字母組成。若其中有多個可行的答案,則返回答案中字典序最小的單詞。

若無答案,則返回空字串。

示例 1:

輸入: 

words = ["w","wo","wor","worl", "world"]

輸出: "world"

解釋: 

單詞"world"可由"w", "wo", "wor", 和 "worl"新增乙個字母組成。

示例 2:

所有輸入的字串都只包含小寫字母。

words陣列長度範圍為[1,1000]。

words[i]的長度範圍為[1,30]。

利用字首樹來解決本題。不過需要改變查詢函式的實現,詳細請見**。

struct trenode

};class trie

~trie() {}

void insert(string s)

ptemp->isword = true;

}bool find(string s) //當傳入單詞的每個字首子串都為詞典裡的單詞時才算找到

return true;

}};class solution

//第二遍查詢最長的單詞

LeetCode 720 詞典中最長的單詞

給出乙個字串陣列words組成的一本英語詞典。從中找出最長的乙個單詞,該單詞是由words詞典中其他單詞逐步新增乙個字母組成。若其中有多個可行的答案,則返回答案中字典序最小的單詞。若無答案,則返回空字串。注意 所有輸入的字串都只包含小寫字母。words陣列長度範圍為 1,1000 words i 的...

720 詞典中最長的單詞

給出乙個字串陣列words組成的一本英語詞典。從中找出最長的乙個單詞,該單詞是由words詞典中其他單詞逐步新增乙個字母組成。若其中有多個可行的答案,則返回答案中字典序最小的單詞。若無答案,則返回空字串。示例 1 輸入 words w wo wor worl world 輸出 world 解釋 單詞...

雜湊 簡單 720 詞典中最長的單詞

class solution def longestword self,words list str str words.sort key lambda x len x x for w in words flag 1for i in range 1 len w 1 if w i not in wor...