题目
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
思路
1.纯暴力解法
2.利用内置函数(…)
3.kmp算法 参考资料
相关思考
在第三种情况中,调试了很久还是发生超时的情况,最后发现在nextval函数中计算发生错误
将
if(needle[j]!=needle[i]) //对next数组进行改进
写为了
if(needle[j]!=needle[next[i])
实际上,当不改进时,所有的next[j]均赋值为i,改进的情况属于当第i位与当前j位置相同时,此时的回溯依然无法匹配上(若一开始没匹配上,大串与小串字符肯定不相等,小串回溯后还是同一个字符,显然依然无法满足条件的),所以此处应该比较的是i位置的字符,而不是next[i]位置的字符。
代码1(C++/原创)
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.empty()) return 0;
if(haystack.empty()) return -1;
if(needle.size()>haystack.size()) return -1;
for(int i=0;i<=haystack.size()-needle.size();i++)
{
int j=0,a=i;
while(haystack[a]==needle[j] && j<needle.size())
{
a++;
j++;
}
if(j==needle.size()) return i;
}
return -1;
}
};
代码2(C++)
class Solution {
public:
int strStr(string haystack, string needle) {
return haystack.find(needle);
}
};
代码3(C++/原创)
class Solution {
public:
void nextval(string& needle,vector<int>& next)
{
int i=-1,j=0;
next[0]=-1;
int len=needle.size();
while(j<len-1)
{
if( i==-1 || needle[i]==needle[j])
{
i++;j++;
if(needle[j]!=needle[i]) //对next数组进行改进
//当需要回溯的位置i上的字符与当前j位置字符一致时,显然依然不能匹配上,所以可以直接赋位置i的next数组的值
{
next[j]=i;
}else{
next[j]=next[i];
}
}else
{
i=next[i];
}
}
}
int strStr(string haystack, string needle) {
if(needle.empty()) return 0;
int i=0,j=0;
int length1=needle.size();
int length2=haystack.size();
vector<int> next(length1);
nextval(needle,next);
while(i<length1 && j<length2)
{
if( i == -1 || haystack[j] == needle[i])
{
i++;j++;
}else{
i=next[i];
}
}
if(i==length1)
{
return j-i;
}
return -1;
}
};