方法一:纵向遍历
遍历每一个字符串的第一个字符,若相同,在前缀p上加上该字符,遍历第二个,若相同,加上p,若不相同。返回p
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size()==0)
{
return "";
}
int j=0;
string p="";
for(int i=0;j<strs.size() && strs[j][i]!='\0'; ++i)
{
while(j<strs.size())
{
if(j==0 || strs[j][i] == strs[j-1][i])
{
j++;
}
else
{
return p;
}
}
p=p+strs[0][i];
j=1;
}
return p;
}
};
方法二:横向遍历
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if (!strs.size()) {
return "";
}
string prefix = strs[0];
int count = strs.size();
for (int i = 1; i < count; ++i) {
prefix = longestCommonPrefix(prefix, strs[i]);//利用前几个字符串的公共前缀和下一个字符串对比求出新的公共前缀
if (!prefix.size()) {
break;
}
}
return prefix;
}
string longestCommonPrefix(const string& str1, const string& str2) {
int length = min(str1.size(), str2.size());
int index = 0;
while (index < length && str1[index] == str2[index]) {
++index;
}
return str1.substr(0, index);
}
};//创建一个函数,求出两字符串的公共前缀
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/longest-common-prefix/solution/zui-chang-gong-gong-qian-zhui-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。