본문 바로가기

Algorithm

[LeetCode] 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 haystack is not part of haystack.

 

needle과 haystack이라는 주어진 두 string값으로 needle이 haystack에 처음 등작하는 index를 반환하여라. needlehaystack에 없는 경우 -1을 반환한다. 

풀이

1. search() 활용 

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
    let position = haystack.search(needle)
    return position;
};

search()는 두개의 스트링을 비교하여 매치되는 첫번째 index를 반한다. 

2. indexOf() 활용

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
    return haystack.indexOf(needle);
};

indexOf()는 string 객체에서 주어진 값과 일치하는 첫 번째 인덱스를 반환합니다. 일치하는 값이 없으면 -1을 반환한다.

 

위 두 메소드가 동일한 기능을 하지만, 시간 복잡도 면에서는 작은 차이가 존재한다. search()의 경우 보다 복잡한 패턴 매칭이 필요할 때 사용하기 용이하며, 단순히 string의 index를 구하는 문제라면 indexOf()를 사용하여 푸는 것이 좋다.

'Algorithm' 카테고리의 다른 글

[LeetCode] Two Sum  (0) 2023.09.18
[LeetCode] Longest Common Prefix  (1) 2023.09.18
[LeetCode] Valid Palindrome  (0) 2023.09.14
[LeetCode]First Unique Character in a String  (0) 2023.09.14
[LeetCode] Reverse Integer  (0) 2023.09.14