나만보는개발공부블로그

Implement strStr() 본문

Algorithms/leetcode

Implement strStr()

alexrider94 2021. 2. 17. 23:15

설명

Implement strStr().

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().

 

Example 1:

Input: haystack = "hello", needle = "ll"

Output: 2

 

Example 2:

Input: haystack = "aaaaa", needle = "bba"

Output: -1

 

Example 3:

Input: haystack = "", needle = ""

Output: 0

/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function (haystack, needle) {
    if (needle.length === 0) return 0;
    for (let i = 0; i < haystack.length; ++i) {
        let j = i, k = 0;
        while (haystack[j] === needle[k] && k < needle.length) {
            j++;
            k++;
        }
        if (k === needle.length) {
            return i;
        }
    }
    return -1;
};

 

'Algorithms > leetcode' 카테고리의 다른 글

Reverse Linked List  (0) 2021.03.23
Valid Palindrome  (0) 2021.03.19
merge-two-sorted-lists  (0) 2021.02.11
Climbing Stair  (0) 2021.02.10
Longest Common Prefix  (0) 2021.02.09