14 Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
Solution
class Solution {
public:
string helper(string s1, string s2) {
string s = "";
int n1 = s1.size(), n2 = s2.size();
if ( n1 == 0 or n2 == 0 ) return s;
for ( int i = 0; i <= min(n1, n2)-1; i++ ){
if ( s1[i] == s2[i] ) s += s1[i];
else return s;
}
return s;
}
string longestCommonPrefix(vector<string>& strs) {
int n = strs.size();
string s = "";
if ( n == 0 ) return s;
s = strs[0];
for ( int i = 1; i <= n-1; i++ ) s = helper(s, strs[i]);
return s;
}
};