LeetCode 14.最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
见过这个题,所以就照搬了,结果发现不对,因为find函数的使用不正确
string containPrefix(vector<string>& s)
{
if(s.empty()) return "";
string prefix=s[0];
for(int i=1;i<s.size();++i)
{
while(s[i].find(prefix)==string::npos)//这句是不对的
{
prefix=prefix.substr(0,prefix.size()-1);
if(prefix.empty())
return "";
}
}
return prefix;
}
只要在字符串中存在prefix,find就能找出,所以可能找到的不是前缀,而是后面的子串,比如
"c","acc","ccc"
"absdfs","abc","aaaab"
按说是可以改,查找的时候从0开始,查找prefix.size()个元素,find定义的重载(第三个)也能实现这个功能,就是运行不了,不知道什么错误
可能是只支持C字符串,不支持string,find还是有很多限制的
size_type find(
value_type _Ch,
size_type _Off = 0) const;
size_type find(
const value_type* ptr,
size_type _Off = 0) const;
size_type find(
const value_type* ptr,
size_type _Off,
size_type count) const;
size_type find(
const basic_string<CharType, Traits, Allocator>& str,
size_type _Off = 0) const;
这样就对了
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.empty())
return "";
string ans=strs[0];
for(int i=1;i<strs.size();++i)
{
while(ans!=strs[i].substr(0,ans.size()))
{
ans=ans.substr(0,ans.size()-1);
if(ans.empty())
return "";
}
}
return ans;
}
};