28. 找出字符串中第一个匹配项的下标
看了一天,说实话,这个题让我感觉我是笨蛋。两个关键点:第一如何实现next数组,第二如何用next数组判定。
class Solution {
public:
void getnext(const string& s, int* next){
int j=0;
next[0]=0;
for(int i=1;i<s.size();i++){
while(j>0 && s[i]!=s[j]){
j=next[j-1];
}
if(s[i]==s[j]){
j++;
}
next[i]=j;
}
}
int strStr(string haystack, string needle) {
if(needle.size()==0){
return 0;
}
int next[needle.size()];
getnext(needle,next);
int j =0;
for(int i=0; i<haystack.size();i++){
while(j>0 && haystack[i]!= needle[j]){
j=next[j-1];
}
if(haystack[i]==needle[j]){
j++;
if(j==needle.size()){
return(i-needle.size()+1);
}
}
}
return -1;
}
};
459.。。周天再补吧得栈了