-
Notifications
You must be signed in to change notification settings - Fork 242
/
Copy pathLongestCommonPrefix.cpp
87 lines (72 loc) · 1.87 KB
/
LongestCommonPrefix.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
79
80
81
82
83
84
85
86
87
// https://leetcode.com/problems/longest-common-prefix/
class TrieNode{
public:
char ch;
TrieNode* children[26];
bool isEnd;
int childCount;
TrieNode(char ch){
this->ch= ch;
for(int i=0; i<26; i++){
children[i]= NULL;
}
isEnd= false;
childCount= 0;
}
};
class Trie {
public:
TrieNode* root;
Trie() {
root= new TrieNode('\0');
}
void insertWord(TrieNode* root, string word){
//Word isEmpty
if(word.length()==0){
root->isEnd= true;
return;
}
int index= word[0] - 'a';
TrieNode* child;
if(root->children[index] != NULL){
child= root->children[index];
}else{
child= new TrieNode(word[0]);
root->children[index]= child;
root->childCount++;
}
insertWord(child, word.substr(1));
}
void insert(string word) {
insertWord(root, word);
}
string getLongestPrefix(string word){
string ans="";
for(int i=0; i<word.length(); i++){
char ch= word[i];
if(root->childCount==1){
ans.push_back(ch);
root= root->children[ch-'a'];
}else{
break;
}
if(root->isEnd)
break;
}
return ans;
}
};
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
Trie* trie= new Trie();
string smallestWord= strs[0];
for(int i=0; i<strs.size(); i++){
trie->insert(strs[i]);
if(i+1<strs.size() && strs[i+1].length()<smallestWord.length()){
smallestWord= strs[i+1];
}
}
return trie->getLongestPrefix(smallestWord);
}
};