컴퓨터공학/LeetCode 1000

[LeetCode] 28. Implement strStr()

saurus2 2022. 8. 17. 14:05

28. Implement strStr()

Easy

Implement strStr().

Given two strings needle and haystack, 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().

 

Example 1:

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

Example 2:

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

 

Constraints:

  • 1 <= haystack.length, needle.length <= 104
  • haystack and needle consist of only lowercase English characters.

문제 풀이

문제 접근

  1. 두가지 문자의 길이가 최대 10^4 이다.
  2. N^2 시간복잡도로 풀 수도 있을 것 같다. 

풀이

  1. neelde 단어가 haystack에 존재할때, 가장 앞에있는 단어를 찾아야한다.
  2. 맨 앞 부터 탐색을 해야 제일 첫번째 인덱스를 구할 수 있다.
  3. 각 인덱스를 needle 단어와 같은지 확인한다.

소스 코드 

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        n = len(needle)
        for i in range(len(haystack) - n + 1):
            temp = haystack[i:i+n]
            if temp == needle:
                return i
        return -1