leetCode
[Easy] 28. Implement strStr()
개발자 자두
2022. 6. 9. 11:16
문제
Implement strStr().
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.
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().
haystack에서 needle 문자열을 찾아 시작하는 인덱스를 반환한다.
만약 needle 문자열을 찾지 못하면 -1을 반환한다.
예시
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
제약 조건
Constraints:
- 1 <= haystack.length, needle.length <= 104
- haystack and needle consist of only lowercase English characters.
해결 과정
haystack에서 needle 문자열을 찾아 index를 반환하는 문제였다.
문제를 읽고 나서 바로 indexOf가 떠올라 쉽게 해결할 수 있었다.
내장 함수를 사용해서 그런지 시간이 조금 오래 걸려서 시간을 단축하는 풀이도 같이 첨부한다
해결 코드
나의 코드
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function(haystack, needle) {
return haystack.indexOf(needle)
};
좀 더 시간복잡도가 빠른 코드
var strStr = function(haystack, needle) {
const needleLength = needle.length;
if(needleLength === 0) return 0;
for(let i = 0 ; i < haystack.length ; i++){
if(haystack.substring(i , i + needleLength) === needle){
return i;
}
}
return -1;
};