728x90
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:
nput: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.
Example 2:
Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.
Constraints:
- 1 <= haystack.length, needle.length <= 10^4
- haystack and needle consist of only lowercase English characters.
Code :
var strStr = function(haystack, needle) {
if (needle === "") return 0; // needle이 빈 문자열인 경우 항상 0을 반환
for (let i = 0; i <= haystack.length - needle.length; i++) {
if (haystack.substring(i, i + needle.length) === needle) {
return i; // 첫 번째 발생 위치를 찾으면 해당 위치를 반환
}
}
return -1; // 발생 위치를 찾지 못한 경우 -1을 반환
};
Solutions Code :
var strStr = function(haystack, needle) {
let n = haystack.length; // haystack의 길이
let m = needle.length; // needle의 길이
if (m === 0) return 0; // 비어있는 needle의 경우 haystack의 첫 인덱스 반환
// haystack을 순회하며 needle 찾기
for (let i = 0; i <= n - m; i++) {
let found = true; // needle이 있는지 확인하는 플래그
for (let j = 0; j < m; j++) {
if (haystack[i + j] !== needle[j]) {
found = false; // 일치하지 않는 문자가 발견되면 플래그를 false로 변경
break;
}
}
if (found) return i; // needle을 찾은 경우 해당 인덱스 반환
}
return -1; // needle을 찾지 못한 경우 -1 반환
}
출처 : https://leetcode.com/problemset/all/
728x90
'LeetCode' 카테고리의 다른 글
[LeetCode] 30. Substring with Concatenation of All Words (0) | 2023.10.30 |
---|---|
[LeetCode] 29. Divide Two Integers (0) | 2023.10.27 |
[LeetCode] 27. Remove Element (0) | 2023.10.27 |
[LeetCode] 26. Remove Duplicates from Sorted Array (0) | 2023.10.27 |
[LeetCode] 25. Reverse Nodes in k-Group (2) | 2023.10.26 |