728x90
48ms 걸리는 내 솔루션
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
m = len(needle)
if len(needle) == 0:
return 0
for i in range(len(haystack)):
if haystack[i] == needle[0] and haystack[i:i+m] == needle:
return i
else:
return -1
20ms 걸리는 솔루션
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
m, n = len(haystack), len(needle)
for i in range(m - n + 1):
if haystack[i: i + n] == needle:
return i
return -1
range 탐색 범위를 애초에 줄였기 때문인듯.
12m
파이썬 find 사용
파이썬 in operator
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle:
return 0
if needle in haystack:
return haystack.find(needle)
else:
return -1
메모리 효율 높은 솔루션
index 메서드 string에도 가능하다는 점.
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle == "":
return 0
try:
index = haystack.index(needle)
return index
except:
return -1
728x90
'Leetcode' 카테고리의 다른 글
[LeetCode] Maximum Subarray 파이썬 (dp, local max, global max) (0) | 2021.03.30 |
---|---|
[LeetCode] Search Insert Position (index) (0) | 2021.03.30 |
[LeetCode] Remove Element 파이썬 (list remove) (0) | 2021.03.29 |
[LeetCode] Merge Two Sorted Lists 파이썬 (linked list) (0) | 2021.03.29 |
[LeetCode] Valid Parentheses 파이썬 (stack, empty stack) (0) | 2021.03.28 |
댓글