Write a function to find the longest common prefix string amongst an array of strings.
其实这个题目说的不是很清楚,有一个条件就是每个字符串都是包含这个前缀的,即不需要去考虑有可能会有两个完全不同的字符串,这也让这个题目简单许多:
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
int n = strs.size();
string res;
if(n == 0)return res;
for(int pos = 0; pos < strs[0].size(); pos++)
{
for(int k = 1; k < n; k++)
{
if(strs[k].size() == pos || strs[k][pos] != strs[0][pos])
return res;
}
res.push_back(strs[0][pos]);
}
return res;
}
};
其中如果循环发现有某个字符串长度小于已判断或发现有不同时,即可直接返回结果,其他情况下一个一个字符加入到结果字符串中即可。