题目:
Write a function to find the longest common prefix string amongst an array of strings.
要求找出所有string的最长前缀。可以选择横向比较,两两比较找出最长的前缀,不断比较,不断更新,但考虑了极端情况,假设相同的最长前缀呈阶梯分布,则做了许多无用功。纵向逐个字符比较,显然简单许多。代码如下:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string res;
int n = strs.size();
if(n == 0) return res;
//if(n == 1) {
// res = strs[0];
// return res;
//}
for(int x = 0; x < strs[0].size(); x++) {
for(int y = 1; y < n; y++) {
if(strs[y].size() < (x+1) || strs[y][x] != strs[0][x]) {
return res;
}
}
res.push_back(strs[0][x]);
}
return res;
}
};