-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonPrefix2.cpp
More file actions
53 lines (46 loc) · 992 Bytes
/
LongestCommonPrefix2.cpp
File metadata and controls
53 lines (46 loc) · 992 Bytes
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
#include<iostream>
#include<string.h>
#include<vector>
using namespace std;
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty()){
return "";
}
return longestCommonPrefix(strs,0,strs.size()-1);
}
string longestCommonPrefix(vector<string>& strs,int l,int r){
if(l==r){
return strs.at(l);
}
else{
int mid=(l+r)/2;
string lcpLeft=longestCommonPrefix(strs,l,mid);
string lcpRight=longestCommonPrefix(strs,mid+1,r);
return commonPrefix(lcpLeft,lcpRight);
}
}
string commonPrefix(string left,string right){
int i=0;
for(;i<left.length()&&i<right.length();i++){
if(left[i]!=right[i]){
break;
}
}
return left.substr(0,i);
}
};
int main(){
vector<string> strs;
int n;
cin>>n;
for(int i=0;i<n;i++){
string str;
cin>>str;
strs.push_back(str);
}
Solution *solution=new Solution();
cout<<solution->longestCommonPrefix(strs);
return 0;
}