Skip to content

Instantly share code, notes, and snippets.

@goh-chunlin
Last active March 4, 2022 10:19
Show Gist options
  • Save goh-chunlin/b5debcdd0d9ffaa37ba0f1f8d8d51713 to your computer and use it in GitHub Desktop.
Save goh-chunlin/b5debcdd0d9ffaa37ba0f1f8d8d51713 to your computer and use it in GitHub Desktop.
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. (Single loop)
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;
for (int i = 0; i < haystack.Length; i++) {
if (j == 0 && haystack.Length - i < needle.Length) return -1;
if (haystack[i] == needle[j]) {
j += 1;
if (j == needle.Length) return i - j + 1;
} else {
i -= j;
j = 0;
}
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment