-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path720.cpp
78 lines (74 loc) · 1.79 KB
/
720.cpp
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
// trie+45ms.cpp
class Solution {
struct trie {
bool isWord = false;
trie *children[26] = {};
} root;
public:
/** Inserts a word into the trie. */
bool insert(string &word) {
trie *p = &root;
bool once = true;
trie *parent;
int child;
for (auto ch : word) {
int offset = ch - 'a';
if (p->children[offset] == nullptr) {
if (once) {
once = false;
p->children[offset] = new trie();
parent = p;
child = offset;
} else {
delete parent->children[child];
parent->children[child] = nullptr;
return false;
}
}
p = p->children[offset];
}
p->isWord = true;
return true;
}
public:
string longestWord(vector<string> &words) {
sort(words.begin(), words.end());
string res = "";
for (auto &word : words)
if (insert(word) && (word.size() > res.size() ||
(word.size() == res.size() && word < res)))
res = word;
return res;
}
};
// trie+49ms.cpp
class Solution2 {
struct trie {
trie *children[26] = {};
} root;
public:
/** Inserts a word into the trie. */
bool insert(string &word) {
trie *p = &root;
for (int i = 0; i < word.size(); ++i) {
int offset = word[i] - 'a';
if (p->children[offset] == nullptr)
if (i == word.size() - 1)
p->children[offset] = new trie();
else
return false;
p = p->children[offset];
}
return true;
}
public:
string longestWord(vector<string> &words) {
sort(words.begin(), words.end());
string res = "";
for (auto &word : words)
if (insert(word) && (word.size() > res.size() ||
(word.size() == res.size() && word < res)))
res = word;
return res;
}
};