-
Notifications
You must be signed in to change notification settings - Fork 1
/
14.cpp
55 lines (49 loc) · 1.18 KB
/
14.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
// 14. Longest Common Prefix - https://leetcode.com/problems/longest-common-prefix
#include "bits/stdc++.h"
using namespace std;
struct TrieNode {
map<char, TrieNode*> next;
};
class Trie {
public:
Trie() : root(new TrieNode) {}
void insert(const string &word) {
auto cur = root;
for (char ch : word) {
if (!cur->next.count(ch)) {
cur->next[ch] = new TrieNode;
}
cur = cur->next[ch];
}
cur->next['#'] = new TrieNode;
}
string lengthOfCommonPrefix() {
string result;
auto cur = root;
while (cur != nullptr && (int)cur->next.size() == 1) {
auto it = cur->next.begin();
char ch = it->first;
if (ch == '#') { break; }
result += ch;
cur = cur->next[ch];
}
return result;
}
private:
TrieNode* root;
};
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
for (const auto &str : strs) {
trie.insert(str);
}
return trie.lengthOfCommonPrefix();
}
private:
Trie trie;
};
int main() {
ios::sync_with_stdio(false);
return 0;
}