g++ (Ubuntu 4.9.2-10ubuntu13) 4.9.2下编译和运行通过
#include<iostream>
#include<string.h>
using namespace std;
int * getnext(char* substr)
{
unsigned int i = 0;
int j = -1;
int n = strlen(substr);
int *next = new int(n);
next[0] = -1;
while (i < strlen(substr))
{
if (j == -1 || substr[i] == substr[j]) {
++i;
++j;
next[i] = j;
}
else {
j = next[j];
}
}
return next;
}
int KMP(char* str, char* substr)
{
int unsigned i = 0, j = 0;
int *next;
next = getnext(substr);
while (i < strlen(str) && j < strlen(substr))
{
if (str[i] == substr[j])
{
++i;
++j;
}
else
{
j = next[j];
if (j == -1)
{
j = 0;
++i;
}
}
}
if (j == strlen(substr))
return (i - strlen(substr));
else
return 0;
}
int main()
{
char* str = "abababc";
char* substr = "abc";
int i = KMP(str, substr);
cout << "This is the result:" << endl;
cout << i << endl;//result = 4
return 0;
}
我在牛客网上implement str的解答:(不知道为什么通不过测试,请指教!)
class Solution {
public:
int strStr(char *haystack, char *needle) {
int i = 0;
int j = 0;
int m = strlen(haystack);
int n = strlen(needle);
int *next = new int[n];
getnext(needle, next);
while (i < m && j < n)
{
if (j == -1 || haystack[i] == needle[j])
{
++i;
++j;
}
else
{
j = next[j];
}
}
if (j >= n)
return (i - j);
else
return -1;
}
void getnext(char *needle, int next[])
{
int i = 0, j = -1;
int n = strlen(needle);
next[0] = -1;
while (i <n) {
if (j == -1 || needle[i] == needle[j])
{
++i;
++j;
next[i] = j;
}
else
j = next[j];
}
}
};