N

(Leet Code c++)Implement strStr() 본문

Leet Code 알고리즘

(Leet Code c++)Implement strStr()

naeunchan 2021. 7. 7. 10:36
728x90
반응형

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.

 

주어진 haystack 문자열 내에서 needle 문자를 찾아, 시작되는 인덱스를 리턴하면 된다.

예외로 needle이 ""로 주어진다면 그냥 0을 리턴하도록 했다.

 

needle이 공백이 아니라면 for문을 이용해 haystack을 needle의 크기만큼 잘라서 비교하면 된다.

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle == ""){
            return 0;
        }
        
        int len = needle.size();
        int answer = -1;
        
        for(int i = 0; i < haystack.size(); i++){
            string current = haystack.substr(i, len);
            
            if(current == needle){
                answer = i;
                break;
            }
        }
        
        return answer;
    }
};

 

728x90
반응형