컴퓨터/Leet me code

Leet me code 6 - [LeetCode][C++] 28. Implement strStr() (Easy)

정대2 2022. 2. 28. 22:49

leet me code!


https://leetcode.com/problems/implement-strstr/

 

Implement strStr() - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

28. Implement strStr()

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

 

Constraints:

  • 0 <= haystack.length, needle.length <= 5 * 104
  • haystack and needle consist of only lower-case English characters.

문제 정리

strStr() 구현하는 문제

주어진 단어 needle이 haystack에 포함된 경우, 처음 needle이 나타난 위치를 반환

haystack안에 포함되지 않은 경우 -1, needle이 empty인 경우 0 리턴

 

생각의 흐름

two pointer

haystack 한글자씩 needle과 비교

needle의 길이만큼 탐색이 된 경우(j == nsize), needle이 포함되었다고 판단하고 그때의 첫 위치 반환(i)

 

Solution 코드

class Solution {
public:
    int strStr(string haystack, string needle) {
        int hsize = haystack.size();
        int nsize = needle.size();
        
        int i = 0;
        while (i <= hsize-nsize) {
            int j = 0;
            while (j < nsize) {
                if (haystack[i+j] != needle[j]) break;
                j++;
            }
            if (j == nsize) return i;
            i++;
        }
        
        return -1;
    }
};