给你两个字符串 haystack
和 needle
,请你在 haystack
字符串中找出 needle
字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle
不是 haystack
的一部分,则返回 -1
。
示例 1:
输入:haystack = "sadbutsad", needle = "sad" 输出:0 解释:"sad" 在下标 0 和 6 处匹配。 第一个匹配项的下标是 0 ,所以返回 0 。
示例 2:
输入:haystack = "leetcode", needle = "leeto" 输出:-1 解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1 。
提示:
1 <= haystack.length, needle.length <= 104
haystack
和needle
仅由小写英文字符组成
注意点:
看了一下c++底层源码,发现c++中对于string的length()方法和size()方法的实现均为
size() const _GLIBCXX_NOEXCEPT
{ return _M_rep()->_M_length; }
但是!!!!
在力扣上面,使用length()方法过不了,但是使用size()可以通过。
如果有知道的大佬们请底下留言
C++代码
class Solution {
private:
int* getNext(string pattern){
int* next=new int[pattern.length()];
int i=0,j=-1;
next[0]=-1;
while(i<pattern.length()-1){
if(j==-1||pattern[i]==pattern[j]){
i++;j++;
next[i]=j;
}else{
j=next[j];
}
}
return next;
}
int KMP(string s,string t){
int* next=getNext(t);
int i,j;
i=0,j=0;
int m=s.size();
int n=t.size();
while(i<m&&j<n){
if(j==-1||s[i]==t[j]){
i++;j++;
}else{
j=next[j];
}
if(j==n){
return i-j;
}
}
return -1;
}
public:
int strStr(string haystack, string needle) {
return KMP(haystack,needle);
}
};