28. Find the Index of the First Occurrence in a String
Source
https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/
Find the Index of the First Occurrence in a String - LeetCode
Can you solve this real interview question? 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 needle is not part of haystack. Example 1: I
leetcode.com
Code
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function (haystack, needle) {
for (let i = 0; i < haystack.length; i++) {
if (haystack[i] === needle[0]) {
if (haystack.slice(i, i + needle.length) === needle) {
return i;
}
}
}
return -1;
};
How to solve?
건초더미를 순회하며 바늘의 첫번째 값과 일치하면 slice 함수를 이용하며 동일한지 검증한다.
'Problem solve' 카테고리의 다른 글
[Leetcode] 48. Rotate Image (Python) (0) | 2023.05.15 |
---|---|
[Leetcode] 11. Container With Most Water (JavaScript) (0) | 2023.05.07 |
[LeetCode] 35. Search Insert Position (Javascript) (0) | 2023.04.24 |
[Leetcode] 14. Longest Common Prefix (0) | 2023.04.18 |
[Leetcode] 2619. Array Prototype Last (Javascript) (0) | 2023.04.12 |