Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
这道题是让我们自己完善函数strStr():返回模式串needle在主串haystack中第一次出现的索引位置,若主串中不存在模式串,则返回-1。解法很容易想到,大二下学期数据结构关于字符串的一章,用KMP算法就可以解决。这里就不自己写KMP到底是怎么实现的了,给一个写的很棒的链接:从头到尾彻底理解KMP(2014年8月22日版)
代码贴上:
class Solution {
public:
void getNextArray(char* needle, int next []){
int len = strlen(needle);
int j = 0, k;
next[j] = -1;
k = next[j];
while (j != len){
if (needle[j] == needle[k] || k == -1){
j++;
k++;
next[j] = k;
}
else{
k = next[k];
}
}
}
int strStr(char *haystack, char *needle) {
int len1 = strlen(needle);//p
int len2 = strlen(haystack);//q
if (len1 > len2)
return -1;
int* next=new int[len1+1];
getNextArray(needle, next);
int p = 0, q = 0;
while (p < len1&&q < len2){
if (haystack[q] == needle[p]){
p++;
q++;
}
else{
if (p == 0)
q++;
else
p = next[p];
}
}
if (p < len1)
return -1;
return q - len1;
}
};原文:http://blog.csdn.net/kaitankedemao/article/details/43524253