본문 바로가기
Leetcode

[LeetCode] Implement strStr() 파이썬 (exhaustive search, find, index string)

by YGSEO 2021. 3. 29.
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

댓글