class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle:
return 0
needle_len = len(needle)
haystack_len = len(haystack)
for i in range(haystack_len-needle_len+1):
temp = haystack[i:i+needle_len]
if temp == needle:
return i
return -1
[문제]
주어진 haystack 스트링 안에서 needle 스트링을 찾는 문제이다
Input: haystack = "hello", needle = "ll" Output: 2
[풀이]
hatstack 스트링 안에서 인덱스를 하나씩 이동하며, needle 사이즈만큼 부분 스트링을 가져온다.
가져온 부분 스트링을 needle 스트링과 비교한다.
같으면 인덱스 반환하고, 같은 부분 스트링이 하나도 발견되지 않을 시, -1 리턴한다.