Implement strStr

Jamie·2022년 2월 25일
0

LeetCode

목록 보기
4/18
post-thumbnail

문제

Implement strStr().

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
Example 3:

Input: haystack = "", needle = ""
Output: 0

Constraints:

0 <= haystack.length, needle.length <= 5 \* 104
haystack and needle consist of only lower-case English characters.

풀이

var strStr = function (haystack, needle) {
    // haystack을 반복문을 돌면서 needle의 첫번째 글자와 찾는 요소를 찾는다
    // 일치하면 그 인덱스부터 needle 글자수만큼 빼낸것과 needle과 일치하는지 비교한다
    // 일치하는 것이 없으면 -1 리턴, needle이 빈 문자열일 때는 0을 리턴한다

    if (needle.length === 0) {
        return 0;
    }
    for (let i = 0; i < haystack.length; i++) {
        if (haystack[i] === needle[0]) {
            if (haystack.substring(i, i + needle.length) === needle) {
                return i;
            }
        }
    }
    return -1;
};

✅ 찾는 조건이 많아서 뭔가 더 간략하게 줄여서 쓸 수 있는 코드가 있지 않을까라는 생각을 했는데 다른 사람들이 푼 방법 중에 haystack.split(needle)[0]로 빼내서 needle과 비교한 분도 있었다.

profile
공부하고 비행하다 개발하며 여행하는 frontend engineer

0개의 댓글