Skip to content

Instantly share code, notes, and snippets.

@goh-chunlin
Last active March 4, 2022 12:09
Show Gist options
  • Save goh-chunlin/4e2e8d8df161325b466679171348de5c to your computer and use it in GitHub Desktop.
Save goh-chunlin/4e2e8d8df161325b466679171348de5c to your computer and use it in GitHub Desktop.
The KMP (Knuth–Morris–Pratt) Algorithm with KMP Table.
public int StrStr(string haystack, string needle) {
if (needle == null || needle == "") return 0;
if (needle.Length > haystack.Length) return -1;
if (needle.Length == haystack.Length) return haystack == needle ? 0 : -1;
int[] lps = ComputeKMPTable(needle);
int i = 0;
int j = 0;
while (i < haystack.Length) {
if (haystack[i] == needle[j]) {
i += 1;
j += 1;
if (j == needle.Length) return i - j;
} else {
if (j != 0)
{
j = lps[j - 1];
}
else
{
i += 1;
}
}
}
return -1;
}
private int[] ComputeKMPTable(string pattern) {
int i = 1;
int j = 0;
int[] lps = new int[pattern.Length];
while (i < pattern.Length) {
if (pattern[i] == pattern[j]) {
j += 1;
lps[i++] = j;
} else {
if (j != 0)
{
j = lps[j - 1];
}
else
{
i += 1;
}
}
}
return lps;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment