[Leetcode] 28. Implement strStr()

Seongjun Lee·2022년 2월 19일
0

[Leetcode] - Problem

목록 보기
28/43
post-thumbnail

Problem

문제 링크

Javascript String 함수중에서 String.prototype.indexOf()를 구현하는 문제

Solution

  1. 찾고자하는 값이 비어있을때는 0을 반납한다.

  2. haystack 문자열을 순서대로 비교하면서 needle의 문자열과 일치하는지 두 반복문을 이용해서 비교한다.

    • 이때 haystack이 남은 문자열수가 needle 보다 적지않도록 조건을 준다.
  3. haystackneedle 문자열이 존재하는 경우 현재 순환중인 haystack의 인덱스를 리턴하고 존재하지않다면 -1을 리턴한다.

JS Code

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
    if (!needle.length) return 0
    
    outer:for(let i = 0 ; i < haystack.length; i++) {
        if (haystack.length - i < needle.length) break
        for(let j = 0 ; j < needle.length; j++) {
            if(haystack[j + i] !== needle[j]) continue outer
        }
        return i
    }
    return -1
};
profile
Hi there 👋

0개의 댓글