[Python] Leetcode 28. Find-the-index-of-the-first-occurence-in-a-string
Leetcode 28 Find the Index of the First Occurrence in a String
문제
Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
풀이
- 시간복잡도: O((n-m+1)*m) = O(nm)
- 공간복잡도: O(1)
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
m = len(haystack)
n = len(needle)
for i in range(m-n+1):
answer = 0
for j in range(n):
if haystack[i+j] != needle[j]:
break
if j == n - 1:
return i
return -1