복's

[ LeetCode - 28 ] Find the Index of the First Occurrence in a String 본문

알고리즘/LeetCode

[ LeetCode - 28 ] Find the Index of the First Occurrence in a String

나복이 2023. 11. 1. 23:58
728x90

https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/

 

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

easy 문제가 재미 있지는 않지만... 

구현 능력 항샹을 위해서라도 꾸준히 해줘야겠다.

다행히도 도움이 전혀 안되는건 아니고, 다른 사람 코드를 참고하면 아직 모르는 파이썬의 기능들도 알게 되어서 나쁘지 않은것 같다.


[ 📌 풀이 ]

주어진 문자의 길이만큼 비교해서 같은 문자가 있는지 찾으면 되는 문제이기 때문에 index만 잘 관리하면 큰 문제는 없이 풀린다.

파이썬은 그냥 == 로 비교만 하면 되서 더 간편한거 같다.


[ 📌  코드 - Python(Sol1) ]

이게 내 첫 풀이였는데 다른 사람들 코드 보니까 비슷하게 짠 코드들이 보여서 안심했다.

"""
# Author    : Lee In Bok 
# Date      : 2023.11.01(Wed)
# Spend Time: 04m 50s
# Runtime   : 36 ms (Beats 72.83%)
# Memory    : 16.2 MB (Beats 73.86%)
# Algoritm  : String
"""

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        h_len, n_len = len(haystack), len(needle)

        for idx in range(h_len - n_len + 1):
            if haystack[idx:idx+n_len] == needle:
                return idx
            
        return -1

[ 📌  코드 - Python(Sol2) ]

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        h_len, n_len = len(haystack), len(needle)

        for i in range(h_len - n_len + 1):
            for j in range(n_len):
                if haystack[i + j] != needle[j]:
                    break
                if j == n_len - 1:
                    return i
            
        return -1

[ 📌 다른 사람 코드 - Python ]

if str in str을 통해서도 안에 포함되어 있는지 알 수 있다는걸 알게 되었다.

find를 통해서 인덱스의 시작 위치도 알 수 있다는걸 알게 되었다.

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        return haystack.find(needle) if needle in haystack else -1

[ 📌 결과 ]

[ Result ]

728x90