LeetCode 720. 詞典中最長的單詞
阿新 • • 發佈:2020-10-18
思路
先將所有單詞存入字典樹。對於每個單詞,在字典樹中檢查它的全部字首是否存在。
程式碼實現
1 class Solution { 2 3 class Trie { 4 public: 5 bool isWord = false; 6 Trie* next[26] = {NULL}; 7 8 Trie(){} 9 void insert(const string& word) { 10 Trie* t = this; 11 for(inti = 0; i < word.length(); ++i){ 12 if(t->next[word[i]-'a'] == NULL) { 13 t->next[word[i]-'a'] = new Trie(); 14 } 15 16 t = t->next[word[i]-'a']; 17 } 18 19 t->isWord = true; 20 } 21 22//檢查word單詞的所有字首是否都在字典樹中 23 bool check(const string& word) { 24 Trie* t = this; 25 for(int i = 0; i < word.length(); ++i){ 26 if(t->next[word[i]-'a']->isWord == false) { 27 return false; 28 } 29 t = t->next[word[i]-'a']; 30 } 31 return true; 32 } 33 34 }; 35 36 public: 37 string longestWord(vector<string>& words) { 38 Trie* t = new Trie(); 39 for(int i = 0; i < words.size(); ++i) { 40 t->insert(words[i]); 41 } 42 43 string ans = ""; 44 for(int i = 0; i < words.size(); ++i) { 45 if(t->check(words[i]) == true) { 46 if(words[i].length() > ans.length()) 47 ans = words[i]; 48 else if(words[i].length() == ans.length() && words[i] < ans) 49 ans = words[i]; 50 } 51 } 52 53 return ans; 54 } 55 };
複雜度分析
時間複雜度:O(所有單詞長度之和),即建立字首樹佔主要。
空間複雜度:O(所有單詞長度之和),建立字首樹耗費的空間。