forked from Manish1Gupta/Coding-Community-Contributions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongest Common Prefix.cpp
More file actions
30 lines (24 loc) · 862 Bytes
/
Longest Common Prefix.cpp
File metadata and controls
30 lines (24 loc) · 862 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
class Solution {
public:
string longestCommonPrefix(vector<string>& str) {
int n = str.size();
if(n==0) return "";
string ans = "";
sort(begin(str), end(str));
string a = str[0];
string b = str[n-1];
for(int i=0; i<a.size(); i++){
if(a[i]==b[i]){
ans = ans + a[i];
}
else{
break;
}
}
return ans;
}
};
// The code below is very much self explanatory.
// We first sort the array of strings.
// Then, we choose the first and last string in the array. [They are supposed to be the most different among all the pairs of strings in the sorted array]
// We just compare how many common characters match from index i = 0 of these two strings.