neetcode/easy/find-the-index-of-the-first-occurence-in-string.py

36 lines
1007 B
Python

#!/usr/bin/python
# yigid balaban <fyb@fybx.dev>
# neetcode 2024
# easy / find the first occurence in a string
# TC: O(n), MC: O(1)
def solution(haystack: str, needle: str) -> int:
ph, pn = 0, 0
position = -1
while ph < len(haystack):
print(ph, haystack[ph], pn, needle[pn])
if haystack[ph] == needle[pn]:
if position == -1:
position = ph
pn += 1
if pn == len(needle):
break
else:
if pn != 0:
ph = position
position, pn = -1, 0
ph += 1
return position if pn == len(needle) else -1
print(solution('sadbutsad', 'sad') == 0)
print(solution('leetcode', 'lecola') == -1)
print(solution('leetcode', 'etc') == 2)
print(solution('a', 'a') == 0)
print(solution('bbbab', 'ab') == 3)
print(solution('bbbaaaab', 'ab') == 6)
print(solution('aa', 'aaa') == -1)
print(solution('a', 'aaa') == -1)
print(solution('mississippi', 'issip') == 4)