관리 메뉴

솜씨좋은장씨

[leetCode] 28. Implement strStr() (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 28. Implement strStr() (Python)

솜씨좋은장씨 2020. 9. 10. 00:15
728x90
반응형

Implement strStr().

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

 

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

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().

 

Constraints:

  • haystack and needle consist only of lowercase English characters.

Solution

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        
        if (haystack == "" and needle == "") or needle == "":
            return 0
        elif haystack == "":
            return -1
        
        split_check = haystack.split(needle)
        
        if split_check[0] == haystack:
            answer = -1
        elif split_check[0] != haystack:
            answer = len(split_check[0])
        
        return answer

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments