Table of contents
Longest Common Prefix
Problem Link:
https://leetcode.com/problems/longest-common-prefix/description/
My approach:
I sorted the array in the ascending order of the string sizes.
Then I checked every character of the arr[0] with others strings.
If they all have that character then I'll add it to my 'ans'.
The moment they don't match I'll return the ans (initiliaze ans = "").
Code:
Using Sorting:
bool comp(string a, string b){
return a.size()<b.size();
}
class Solution {
public:
string longestCommonPrefix(vector<string>& arr) {
sort(arr.begin(), arr.end(), comp);
string ans = "";
int n = arr.size();
int m = arr[0].size();
for(int i=0;i<m;i++){
char ch = arr[0][i];
for(int j=1;j<n;j++){
if(arr[j][i]!=ch){
return ans;
}
}
ans += ch;
}
return ans;
}
};