Write a function to find the longest common prefix string amongst an array of strings.
Subscribe to see which companies asked this question
就是比较vector<string>中,从头开始字符串相同的部分。。
就是第一个字符串和下面的进行比较,取相同的部分。
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
if (strs.size() == 0)
return "";
string temp = strs[0];
for (int i = 1; i < strs.size(); ++i)
{
if (temp.length() == 0 || strs[i].length() == 0)
return "";
int len = temp.length() < strs[i].length() ? temp.length() : strs[i].length();
int j;
for (j = 0; j < len; ++j)
{
if (temp[j] != strs[i][j]) break;
}
temp = temp.substr(0,j);
}
return temp;
}
};
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 = 0; j < strs.size() - 1; ++j) {
if (i >= strs[j].size() || strs[j][i] != strs[j + 1][i]) {
return strs[j].substr(0, i);
}
}
}
return strs[0];
}
};