Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
解题思路
很简单,没什么可说的。
class Solution {
private:
string getCommonPrefix(string str1, string str2) {
int i = 0, j = 0;
int len1 = str1.length();
int len2 = str2.length();
string prefix;
while(i < len1 && j < len2) {
if (str1[i] != str2[j]) break;
prefix += str1[i];
++i, ++j;
}
return prefix;
}
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.size() == 0)
return "";
string commonPrefix = strs[0];
for (int i = 1; i < strs.size(); ++i) {
commonPrefix = getCommonPrefix(commonPrefix, strs[i]);
}
return commonPrefix;
}
};