Leetcode: String in String
A classic find the needle
in the haystack
problem. The task is to find if a string is contained within another string and return the index of the first position. If the string is not contained return -1
and if the needle
is empty, return 0
.
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle == "":
return 0
h = 0
n = 0
while h < len(haystack):
if haystack[h] == needle[n]:
n += 1
else:
h -= n
n = 0
h += 1
if n == len(needle):
return h - n
return -1
if __name__ == '__main__':
r = Solution().strStr
print(r("mississippi", "issip"), 4)
print(r("hello", 'll'), 2)
print(r('a','a'), 0)