-
Notifications
You must be signed in to change notification settings - Fork 0
/
14. Longest Common Prefix.cpp
132 lines (121 loc) · 3.19 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
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
122
123
124
125
126
127
128
129
130
131
132
//DAY 10 PROBLEM 1
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()==true)
return "";
if(strs.size()==1)
return strs[0];
int flag=0;
string ans="";
for(int j=0;j<strs[0].size();j++)//we have to use strs[0].size() here... we cannot use untill flag==0 as in case of longest common prefix of ["flower","flower"], flag
//never becomes 0.
{
if(strs[j]==""&&j<strs.size())
break;
char x=strs[0][j];
for(int i=1;i<strs.size();i++)
{
if(strs[i][j]==x)
{
if(i==strs.size()-1)
ans+=x;
}
else
{
flag=1;
break;
}
}
if(flag==1)
break;
}
return ans;
}
};
//Using Trie
class TrieNode{
public:
bool isTerminal;
TrieNode* children[26];
char data;
TrieNode(char ch){
ch=data;
for(int i=0;i<26;i++){
children[i]=NULL;
}
isTerminal=false;
}
};
class Solution {
public:
TrieNode* root;
Solution(){
root = new TrieNode('\0');
}
void insertUtil(TrieNode* rootLocal, string word)
{
TrieNode* child;
if(word.size()==0)
{
rootLocal->isTerminal=true;
return;
}
int index = word[0]-'a';
if(rootLocal->children[index]!=NULL)//PRESENT
{
child=rootLocal->children[index];
}
else //ABSENT
{
child= new TrieNode(word[0]);
rootLocal->children[index]=child;
}
insertUtil(child,word.substr(1));
}
bool searchPrefixUtil(TrieNode* rootLocal, string prefix){
TrieNode* child;
if(prefix.size()==0)
return true;
int index= prefix[0]-'a';
if(rootLocal->children[index]!=NULL)//PRESENT
{
int count_of_children=0;
for(int i=0;i<26;i++)
{//rootLocal->isTerminal==false imp to check as in ab and a if isterminal is not checked then ab will be ans. You have to also check ifg any string is not eliminating in the prefix
if(rootLocal->isTerminal==false&&rootLocal->children[i]!=NULL)
count_of_children++;
}
if(count_of_children==1)//logic for prefix
child=rootLocal->children[index];
else
return false;
}
else//ABSENT
{
return false;
}
return searchPrefixUtil(child,prefix.substr(1));
}
string longestCommonPrefix(vector<string>& strs) {
string ans="";
for(int i=0;i<strs.size();i++)
{
// cout<<"insert "<<strs[i]<<endl;
insertUtil(root,strs[i]);
}
for(int i=0;i<=strs[0].size();i++)//<= as in substr function, 2nd argument is length
{
if(searchPrefixUtil(root,strs[0].substr(0,i)))
{
cout<<strs[0].substr(0,i)<<endl;
if(ans.size()==0||((strs[0].substr(0,i)).size()>ans.size()))
{
// cout<<"prefix found "<<strs[0].substr(0,i)<<endl;
ans=strs[0].substr(0,i);
}
}
}
return ans;
}
};