Search

Find the Index of the First Occurrence in a String

문제 설명 : haystack 문자열 내부에 needle과 동일한 단어가 몇번째 인덱스부터 시작되는지 반환, 없다면 -1 반환
풀이 방법
최대한 소요 시간을 줄이기 위해, 첫 단어를 1차로 비교 후, 슬라이스를 사용한 단어 비교를 하였다.
시간복잡도 : O(N2)O(N^2)
성공 코드
# O(N^2) class Solution: def strStr(self, haystack: str, needle: str) -> int: # 첫 글자 우선 확인 후, 단어가 일치한지 확인 # O(N^2) for i in range(len(haystack) - len(needle) + 1): if haystack[i] == needle[0] and haystack[i:i + len(needle)] == needle: return i return -1
Python
복사