原题:
Write a function to find the longest common prefix string amongst an array of strings.
思路:pre赋给第一个strs值,然后和后面的string一个一个比对,一旦不相同就砍掉后面的部分,最后返回pre。
代码:
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
if(strs.empty()) return "";
string pre = strs[0];
int len;
for(int i = 1; i<strs.size(); i++){
if(pre==""||strs[i]=="") return "";
len = pre.length() > strs[i].length()? strs[i].length() : pre.length();
int j = 0;
for( ; j<len; j++){
if(pre[j]!=strs[i][j]) break;
}
pre = pre.substr(0,j);
}
return pre;
}
};