오늘도 개발

22. Find the Index of the First Occurrence in a String 본문

자료구조 & 알고리즘/Leetcode

22. Find the Index of the First Occurrence in a String

Sueeeeeee 2022. 10. 12. 16:47

문제

needle과 haystack이라는 문자열을 받아 haystack에 있는 needle의 첫 번째 인덱스를 반환하라.

needle이 haystack에 없으면 -1을 반환하라.

 

내가 해결한 방식

문제점 : 느림(5.64%)

def strStr(self, haystack: str, needle: str) -> int:
    # haystack을 i로 하나씩 iterate 
    for i in range(len(haystack)):
        # haystack에서 needle의 첫 글자와 똑같은 글자가 나오는 경우
        if haystack[i] == needle[0]:
            result = 1
            # needle을 j로 iterate
            for j in range(1, len(needle)):
                haystack_index = i + j
                # haystack보다 needle의 길이가 긴 경우 
                if haystack_index >= len(haystack):
                    break
                # haystack과 needle의 글자가 일치하는 경우 
                if haystack[haystack_index] == needle[j]:
                    result += 1
            if result == len(needle):
                return i 
    return -1

 

다른 해결 방식

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

인덱스 슬라이싱 사용

def strStr(self, haystack, needle):
    needle_length, haystack_length = len(needle), len(haystack)
    if needle_length > haystack_length:
        return -1
    if needle_length == 0:
        return 0

    for i in range(haystack_length - needle_length + 1):
        if haystack[i:i+needle_length] == needle:
            return i
    return -1

'자료구조 & 알고리즘 > Leetcode' 카테고리의 다른 글

24. Reverse String  (1) 2022.10.14
23. Longest Common Prefix  (0) 2022.10.14
21. Add Binary  (0) 2022.10.11
20. Pascal's Triangle  (1) 2022.09.23
19. Spiral Matrix  (1) 2022.09.22