-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy path14. Longest Common Prefix.cpp
50 lines (39 loc) · 1.02 KB
/
14. Longest Common Prefix.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
class Solution {
public:
Solution() {
root = new trie;
}
string longestCommonPrefix(vector<string>& strs) {
string prefix = "";
for (int i = 0; i < strs.size(); ++i) {
prefix = insert(strs[i], strs.size());
}
return prefix;
}
private:
struct trie {
int prefixes;
trie *next[26];
trie() {
prefixes = 0;
for (int i = 0; i < 26; ++i)
next[i] = NULL;
}
};
trie *root;
string insert(string s, int strCount) {
string prefix = "";
trie *cursor = root;
for(int i = 0; s[i] != '\0'; ++i) {
int number = s[i] - 'a';
if(cursor->next[number] == NULL)
cursor->next[number] = new trie;
cursor = cursor->next[number];
cursor->prefixes++;
if (cursor->prefixes == strCount) {
prefix += s[i];
}
}
return prefix;
}
};