記錄

28. Find the Index of the First Occurrence in a String 본문

FRONTEND STUDY/LeetCode

28. Find the Index of the First Occurrence in a String

prts 2022. 10. 28. 01:37

문제 링크: https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/
난이도: Medium

 

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.

 

두 개의 문자열 needle과 haystack이 주어지면, haystack에서 needle이 처음 나타나는 index를 반환하거나, needle이 haystack의 일부가 아닌 경우 -1을 반환합니다.

 

Example 1:

Input: 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 <= 104
  • haystack and needle consist of only lowercase English characters.

Related Topics: Two Pointers, String, String Matching

 


문제 풀이
//내장 메소드 활용
var strStr = function(haystack, needle) {
    //haystack에서 첫번째로 등장하는 needle의 index
    if (haystack.includes(needle)) return haystack.indexOf(needle);
    else return -1;
};
//for문
var strStr = function(haystack, needle) {
    if (needle.length===0) return 0;
    
    for (let i=0;i<haystack.length;i++){
        for (let j=0;j<needle.length;j++){
            if (needle[j] !== haystack[i+j]) break;
            if (needle.length-1===j) return i;
        }
    }
    return -1;
};

 

'FRONTEND STUDY > LeetCode' 카테고리의 다른 글

48. Rotate Image  (0) 2022.11.19
3. Longest Substring Without Repeating Characters  (0) 2022.11.05
20. Valid Parentheses  (0) 2022.10.25
120. Triangle  (0) 2022.10.24
[JS] 386. Lexicographical Numbers  (0) 2022.10.20
Comments