Longest Common Prefix

Desicription

Write a function to find the longest common prefix string amongst an array of strings.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size() == 0)
return "";
string res;
for(int i = 0; strs[0][i]; i++){
for(int j = 0; j < strs.size(); j++){
if(strs[j][i] != strs[0][i] || strs[j].size() == i)
return res;
}
res += strs[0][i];
}
return res;
}
};