얼렁뚱땅 스며드는 Data Science

Algorithm/Daily Coding Tests Challenge

[Leetcode] Easy : Implement strStr()

Jesip14 2021. 9. 4. 16:16

Description

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 solution

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