14. Longest Common Prefix
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string res = "";
if (strs.size() == 0)
return res;
for (int i = 0; i < strs[0].size(); res += strs[0][i], i++)
for (int j = 1; j < strs.size(); j++)
if (strs[j].size() < i || strs[j][i] != strs[0][i])
return res;
return res;
}
};
pay attention to the i = 1!!!!!!!!!!!
if no using res to record, it will return 0;
the bad example
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.size() == 0)
return "";
for (int i = 0; i < strs[0].size(); i++)
for (int j = 1; j < strs.size(); j++)
if (strs[j].size() < i || strs[j][i] != strs[0][i]) {
if (i > 0)return strs[0].substr(0, i);
else return "";
}
return "";
}
};