Skip to content

Commit f2de943

Browse files
Add files via upload
1 parent afa2283 commit f2de943

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
// 首先需要对给定的字典建立一个前缀树,然后使用深度优先搜索进行查找
2+
3+
// Runtime: 52 ms, faster than 84.90% of C++ online submissions for Longest Word in Dictionary.
4+
// Memory Usage: 29.5 MB, less than 30.00% of C++ online submissions for Longest Word in Dictionary.
5+
6+
struct TrieNode
7+
{
8+
bool isWord = false;
9+
TrieNode* next[26] = {nullptr};
10+
};
11+
12+
class Solution
13+
{
14+
public:
15+
16+
Solution () : root(new TrieNode()) {}
17+
18+
~Solution () { clear(root); }
19+
20+
string longestWord(vector<string>& words)
21+
{
22+
// 建立字典树
23+
buildTire(words);
24+
25+
string res = "", candidate = "";
26+
27+
dfs(root, res, candidate);
28+
29+
return res;
30+
}
31+
private:
32+
TrieNode* root = nullptr;
33+
34+
private:
35+
void buildTire(vector<string>& words)
36+
{
37+
// 迭代插入
38+
for (auto word : words)
39+
{
40+
TrieNode* head = root;
41+
42+
for (int index = 0; index < word.length(); ++index)
43+
{
44+
if (head->next[word[index] - 'a'] == nullptr)
45+
{
46+
TrieNode* node = new TrieNode();
47+
head->next[word[index] - 'a'] = node;
48+
}
49+
head = head->next[word[index] - 'a'];
50+
if (index == word.length() - 1)
51+
head->isWord = true;
52+
}
53+
}
54+
}
55+
56+
void dfs(TrieNode* root, string& res, string& candidate)
57+
{
58+
if (root == nullptr)
59+
return ;
60+
61+
for (int i = 0; i < 26; ++i)
62+
{
63+
if (root->next[i] != nullptr && root->next[i]->isWord)
64+
{
65+
candidate.push_back('a' + i);
66+
67+
if (candidate.length() > res.length() || (candidate.length() == res.length() && candidate < res))
68+
res = candidate;
69+
70+
dfs(root->next[i], res, candidate);
71+
72+
candidate.pop_back();
73+
}
74+
}
75+
}
76+
77+
void clear(TrieNode* root)
78+
{
79+
if (root == nullptr)
80+
return ;
81+
82+
for (int i = 0; i < 26; ++i)
83+
clear(root->next[i]);
84+
delete root;
85+
}
86+
};

0 commit comments

Comments
 (0)