본문 바로가기
LeetCode/Top Interview Q. - Easy

LeetCode. Implement strStr() [String]

by 벤진[Benzene] 2020. 6. 2.

Problem:

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

 

-Summary-

1. Check if needle str is in haystack str if not, return False.

2. using index() method to find the first occurrence of the needle in a haystack.

 

Discussion을 보니 아래와 같이 method 를 이용하지 않고 푸는 방법도 있었다.

leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/885/discuss/12814/My-answer-by-Python

class Solution(object):
def strStr(self, haystack, needle):
    """
    :type haystack: str
    :type needle: str
    :rtype: int
    """
    for i in range(len(haystack) - len(needle)+1):
        if haystack[i:i+len(needle)] == needle:
            return i
    return -1

 

모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]

댓글