부부의 코딩 성장 일기

LeetCode 28(Find the Index of the First Occurence in a String, Python) 본문

Algorithm/LeetCode

LeetCode 28(Find the Index of the First Occurence in a String, Python)

펩시_콜라 2023. 11. 3. 19:00

1. 문제 링크

 

Find the Index of the First Occurrence in a String - LeetCode

Can you solve this real interview question? Find the Index of the First Occurrence in a String - 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: I

leetcode.com

2. 문제 설명

  • needle, haystack을 변수명으로 하는 두가지 string이 주어졌을 때, needle이 haystack 안에서 처음으로 나타나는 위치의 인덱스를 반환, 만약 needle이 haystack에 포함되어 있지 않으면 -1을 반환
    • 예시1) haystack="sadbutsad", needle="sad"이면 sad가 index 0에서 처음 등장하여, 0을 return
    • 예시2) haystack="leetcode", needl="leeto"이면 "leeto"는 "leetcode"에 등장하지 않으므로, -1을 return

3. 처음 풀이 

  • 우선 haystack에 needle이 포함되있지 않으면 -1을 반환하고,
  • 그 외의 경우에는, haystack의 index를 needle의 길이만큼 slicing하면서 needle과 같아지는 시작 index를 반환.
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if needle not in haystack: # haystack에 needle이 없으면 -1을 반환
            return -1 
        else:
            for index, i in enumerate(haystack): 
                if haystack[index:index+len(needle)] == needle: # needle length만큼 index를 slicing하면서, needle과 같으면 index를 반환
                    return index
  • runtime beat 86.3%으로 괜찮은 결과가 나왔음

4. 다른 풀이 

  • 애초에 python 문자열에는 .index라는 함수가 있었다. 
  • haystack에 needle이 없으면 -1, 있으면 haystack.index(needle)을 반환
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if needle in haystack:
            return haystack.index(needle)
        else:
            return -1
  • 더 짧게 푸는 풀이도 찾았는데, index 대신 find를 쓰면 if ~ else가 한번에 처리된다.
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        return haystack.find(needle)

5. 배운 점 

  • string에 있는 몰랐던 함수들 (find, index)에 대해 알게 되었다.
  • 그래도 알고리즘 배우는 관점에선 첫번째 한 풀이가 나쁘진 않은듯 하다.