Skip to content

Instantly share code, notes, and snippets.

@jasonlvhit
Last active August 29, 2015 13:56
Show Gist options
  • Save jasonlvhit/9290037 to your computer and use it in GitHub Desktop.
Save jasonlvhit/9290037 to your computer and use it in GitHub Desktop.
很久之前的KMP
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
void match_list(char * pattern, int match[] , size_t len)
{
memset(match, 0 ,sizeof(int)*len);
int i = 0,j = 1;
while(j <= len)
{
if (pattern[j] == pattern [i])
{
match[j] = match[j-1] + 1;
++i;
}
else{
i = 0;
}
j++;
}
}
int main()
{
char* pattern = "a";
int match[strlen(pattern)];
match_list(pattern, match, strlen(pattern));
char* string = "jason";
int i = 0;
int j = 0;
while(i <= strlen(string))
{
if (string[i] == pattern[j])
{
j++;
if(j == strlen(pattern))
{
cout << i - j + 1;
break;
}
}
else{
j = j - match[j];
}
++i;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment