[leetcode-python3] 28. Implement strStr()

28. Implement strStr() - python3

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

My Answer 1: Accepted (Runtime: 24 ms - 95.74% / Memory Usage: 14.5 MB - 27.00%)

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if needle not in haystack:
            return -1
        if needle == "":
            return 0
        
        return haystack.index(needle)

needle 이 haystack 안에 없으면 (not in) => -1 리턴
needle 이 빈 문자열이면 => 0 리턴
나머지는 haystack 속 needle 의 인덱스를 리턴

not in 과 index 덕분에 3분컷으로 풀었다..
파이썬을 사랑하게 됐어요^^

좋은 웹페이지 즐겨찾기