Skip to content

Instantly share code, notes, and snippets.

@goh-chunlin
Last active March 4, 2022 10:16
Show Gist options
  • Save goh-chunlin/b463eaf0f01ef85388f8ed720c81814f to your computer and use it in GitHub Desktop.
Save goh-chunlin/b463eaf0f01ef85388f8ed720c81814f to your computer and use it in GitHub Desktop.
The KMP (Knuth–Morris–Pratt) Algorithm.
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 j = 0;
int nextMatchingHeadIndex = 0;
bool isMatchingHeadFound = false;
for (int i = 0; i < haystack.Length; i++)
{
if (j == 0 && haystack.Length - i < needle.Length) return -1;
if (!isMatchingHeadFound)
{
if (j > 0 && haystack[i] == needle[0])
{
nextMatchingHeadIndex = i - 1;
isMatchingHeadFound = true;
}
else
{
nextMatchingHeadIndex = i;
}
}
if (haystack[i] == needle[j])
{
j += 1;
if (j == needle.Length) return i - j + 1;
}
else
{
i = nextMatchingHeadIndex;
j = 0;
isMatchingHeadFound = false;
}
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment