-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathLeetCode_720_41.cpp
More file actions
121 lines (112 loc) · 2.44 KB
/
LeetCode_720_41.cpp
File metadata and controls
121 lines (112 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/*
* @lc app=leetcode id=720 lang=cpp
*
* [720] Longest Word in Dictionary
* Trie + DFS
* T(n) = O(key_length)
* S(n) = O(26 * key_length *N)
*/
class TrieNode
{
public:
char data;
vector<TrieNode *> children;
bool isEndingChar;
TrieNode(char c) : data(c), children(26, nullptr), isEndingChar(false)
{
}
~TrieNode()
{
for (TrieNode *child : children)
{
if (child)
delete child;
}
}
};
class Trie
{
public:
void insert(string s)
{
TrieNode *p = root;
for (auto c : s)
{
int index = c - 'a';
if (p->children[index] == nullptr)
{
TrieNode *newNode = new TrieNode(c);
p->children[index] = newNode;
}
p = p->children[index];
}
p->isEndingChar = true;
}
bool find(string pattern)
{
TrieNode *p = root;
for (auto c : pattern)
{
int index = c - 'a';
if (p->children[index] == nullptr)
{
return false;
}
p = p->children[index];
}
return p->isEndingChar;
}
bool startsWith(string pattern)
{
TrieNode *p = root;
for (auto c : pattern)
{
int index = c - 'a';
if (p->children[index] == nullptr)
return false;
p = p->children[index];
}
return true;
}
TrieNode *root = new TrieNode(' ');
};
class Solution
{
public:
string longestWord(vector<string> &words)
{
if (words.size() == 0)
return res;
Trie *trieTree = buildTrie(words);
dfs(trieTree->root, "");
return res;
}
private:
Trie *buildTrie(vector<string> &words)
{
Trie *t = new Trie();
for (string w : words)
{
t->insert(w);
}
return t;
}
void dfs(TrieNode *root, string curr)
{
if (root == nullptr)
return;
for (int i = 0; i < 26; i++)
{
if (root->children[i] != nullptr &&
root->children[i]->isEndingChar == true)
{
curr.append(1, i + 'a');
if (curr.size() > res.size())
res = curr;
dfs(root->children[i], curr);
curr.pop_back();
}
}
}
string res = "";
};