-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongest_common_prefix.cpp
More file actions
44 lines (35 loc) · 1 KB
/
longest_common_prefix.cpp
File metadata and controls
44 lines (35 loc) · 1 KB
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
#include <iostream>
using namespace std;
string longestCommonPrefix (string arr[], int N)
{
// your code here
string ans = "";
for(int i = 0; i<arr[0].length(); i++){
char ch = arr[0][i];
bool match = true;
for(int j = 1; j<N; j++){
if(arr[j].size() < i || ch != arr[j][i]){
match = false;
break;
}
}
if(match == false){
break;
}else{
ans.push_back(ch);
}
}
if(ans.length()){
return ans;
}
return "-1";
}
int main(){
int n = 4;
string arr[] = {"geeksforgeeks", "geeks", "geek","geezer"};
string strs[] = {"flower","flow","flight"};
//string ans = longestCommonPrefix (strs,3);
string ans = longestCommonPrefix (arr,n);
cout<<"Required longest common prefix is : "<<ans<<endl;
return 0;
}