分类:algorithm| 发布时间:2016-07-02 15:49:00
Write a function to find the longest common prefix string amongst an array of strings.
找出一组字符串的最长公共前缀。
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) {
return string();
}
string ret = strs[0];
int retSize = ret.size();
const int size = strs.size();
for (int i = retSize - 1; i >= 0; --i) {
for (int j = 1; j < size; ++j) {
if (strs[j].size() < i + 1 || strs[j][i] != ret[i]) {
retSize = i;
break;
}
}
}
ret.resize(retSize);
return ret;
}
};
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) return "";
string res="";
int i = 0;
while (true) {
for (int j = 0; j < strs.size(); j++) {
if (i == strs[j].size() || strs[j][i] != strs[0][i]) {
return res;
}
}
res +=strs[0][i];
i++;
}
}
};