본문 바로가기

알고리즘 스터디

[Leetcode/파이썬] 28. Find the Index of the First Occurrence in a String

반응형

Find the Index of the First Occurrence in a String

Difficulty: Easy


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.

 

Example 1:

Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.

Example 2:

Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.

 

Constraints:

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

 

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if len(haystack) < len(needle) :
            return -1

        if needle not in haystack :
            return -1

        for left in range(len(haystack)) :
            right = left
            while haystack[right] == needle[right - left] :
                right += 1
                if len(needle) == right - left :
                    return left
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        n, m = len(haystack), len(needle)
        if n < m :
            return -1

        if needle not in haystack :
            return -1

        for left in range(n) :
            if haystack[left:left+m] == needle :
                return left

        return -1

딱히 풀이가 필요없는 문제라고 생각한다. 첫 글자를 하나 잡아서 needle의 길이만큼 잡았을 때, needle 과 동일하면 정답처리. 문제대로만 풀이하면 어려움 없이 해결이 가능하다. 

반응형