Skip to content

Instantly share code, notes, and snippets.

@zsh-89
Created November 20, 2013 07:07
Show Gist options
  • Save zsh-89/7558951 to your computer and use it in GitHub Desktop.
Save zsh-89/7558951 to your computer and use it in GitHub Desktop.
class Solution {
public:
char *strStr(char *haystack, char *needle) {
if (!haystack || !needle) return NULL;
int N=strlen(needle);
if (N<1) (haystack[0]=='\0') ? haystack : NULL;
int *next=new int[N];
computeNext(needle, next, N);
char *p=haystack; int j=0;
while (*p && j<N) {
if (j==-1 || *p==needle[j]) ++p, ++j;
else j=next[j];
}
delete [] next;
if (j<N) return NULL;
return p-N;
}
void computeNext(char *pat, int next[], int N) {
next[0]=-1; int i=1, j=-1;
while (i<N) {
if (j==-1 || pat[i-1]==pat[j]) next[i++]=++j;
else j=next[j];
}
}
};
@zsh-89
Copy link
Author

zsh-89 commented Nov 20, 2013

KMP algorithm.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment