LeetCode

28. Implement strStr() c++

O_x 2022. 7. 7. 11:05
28. Implement strStr()
Easy
44483768Add to ListShare

Implement strStr().

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.

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

 

class Solution {
public:
    int strStr(string haystack, string needle) {
        int len = needle.size();
        
        if (haystack.size() < len) return -1;
        
        for (int idx=0; idx <= haystack.size()- len; idx++){
            if (string (haystack.begin()+idx, haystack.begin()+idx+len) == needle) 
                return idx;
        }
        return -1;
    }
};

이 문제는 간단하게 풀 수 있다 haystack을 len을 길이 만큼씩 조사하여 needle과 같은 값이 있는지 찾아 주기만 하면된다

운영중인 카톡방입니다.

https://open.kakao.com/o/gsMhUFie

 

C/C++/C# 언리얼/유니티 /질문

#C++#C#언리얼#게임개발#질문#개발#자료구조#백준#프로그래머스#c#유니티#unity#enreal

open.kakao.com