Write a function to find the longest common prefix string amongst an array of strings.
寻找一组字符串的最长公共前缀,比较简单,直接贴上程序:
accepted answer:
class Solution {
public:
string longestCommonPrefix(vector<string> &strs)
{
string prefix;
if (strs.empty()) return "";
prefix = strs[0];
for (int i = 0; i < strs.size(); i++)
{
int len1 = prefix.length();
int len2 = prefix.length();
int j = 0;
while (j < len1&&j < len2&&prefix[j] == strs[i][j]) j++;
prefix = prefix.substr(0, j);
}
return prefix;
}
};