Write a function to find the longest common prefix string amongst an array of strings.
Personal tips:就是每一个字符串从头开始遍历,代码如下:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (strs.empty()) { string s; return s; }
int end = -1, i = 0, j = 0;
for (; strs[i][j] != '\0'; ++j)
{
for (; strs[i][j] != '\0' &&i < strs.size()-1; ++i)
{
if (strs[i][j] != strs[i + 1][j])
{
return strs[0].substr(0, j);
}
}
if (strs[i][j] == '\0') { end = j - 1; break; }
else end = j;
i = 0;
}
return strs[0].substr(0, end+1);
}
};