Problem:
Write a function to find the longest common prefix string amongst an array of strings.
Solution:
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int size = strs.size();
if (size == 0)
return "";
else if (size == 1)
return strs[0];
else if (size == 2) {
return find_min(strs[0], strs[1]);
} else {
vector<string> first(strs.begin(), strs.begin() + size/2);
vector<string> second(strs.begin() + size/2, strs.end());
return find_min(longestCommonPrefix(first),
longestCommonPrefix(second));
}
}
string find_min(string first, string second) {
string sol;
int str_size = min(first.size(), second.size());
for (int i = 0; i < str_size; i++) {
if (first[i] == second[i])
sol.push_back(first[i]);
else
break;
}
return sol;
}
};
No comments:
Post a Comment