Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解题思路:
1、暴力法。逐一匹配,然后回溯。代码如下,但是产生超时错误。
class Solution {
public:
int strStr(string haystack, string needle) {
int len1=haystack.length();
int len2=needle.length();
if(len2>len1){
return -1;
}
for(int i=0; i<len1; i++){
int j=0;
for(; j<len2&&i+j<len1; j++){
if(haystack[i+j]!=needle[j]){
break;
}
}
if(j==len2){
return i;
}
}
return -1;
}
};class Solution {
public:
int strStr(string haystack, string needle) {
int len1=haystack.length();
int len2=needle.length();
if(len2>len1){
return -1;
}
if(len2==0){
return 0;
}
int next[len2];
next[0]=-1;
int i=0, j=-1;
while(i<len2){
if(j==-1||needle[j]==needle[i]){
i++;
j++;
next[i]=j;
}else{
j=next[j];
}
}
i=0; j=0;
while(i<len1){
if(j==-1||haystack[i]==needle[j]){
i++;
j++;
}else{
j=next[j];
}
if(j==len2){
return i-len2;
}
}
return -1;
}
};原文:http://blog.csdn.net/kangrydotnet/article/details/45246869