Skip to content

Instantly share code, notes, and snippets.

@mylons
Created March 7, 2019 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mylons/823c8b8c04b56f3dd4d08ece40c79ff9 to your computer and use it in GitHub Desktop.
Save mylons/823c8b8c04b56f3dd4d08ece40c79ff9 to your computer and use it in GitHub Desktop.
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle == "":
return 0
if len(haystack) == 1 or len(haystack) == len(needle):
return 0 if haystack == needle else -1
if len(needle) > len(haystack):
return -1
h_pos = 0
while h_pos < len(haystack):
n_pos = 0
while n_pos < len(needle) and h_pos < len(haystack) and haystack[h_pos] == needle[n_pos]:
n_pos += 1
h_pos += 1
if n_pos == len(needle):
return h_pos - n_pos
h_pos = (h_pos - n_pos) + 1
return -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment