-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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