forked from iamAnki/CPP-Programs-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlongest_common_prefix.cpp
46 lines (43 loc) · 1.05 KB
/
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
#include <bits/stdc++.h>
using namespace std;
string longestCommonPrefix(vector<string>& strs) {
string ans = "";
int k = 0;
int n = strs.size();
int flag = 0;
//finding the smallest sized word
int min_size = INT_MAX;
for(int i=0;i<n;i++){
int size = strs[i].size();
min_size = min(min_size, size);
}
while(k < min_size){
int i;
for(i=1;i<n;){
if(strs[i][k] == strs[i-1][k]) i++;
else {
flag = 1;
break;
}
}
if(flag == 1) break;
else{
ans += strs[i-1][k];
k++;
}
}
return ans;
}
int main() {
int n;
vector<string>vec;
cin >> n;
for(int i=0;i<n;i++){
string str;
cin >> str;
vec.push_back(str);
}
string ans = longestCommonPrefix(vec);
cout << ans << endl ;
return 0;
}