본문 바로가기
LeetCode

28. Implement strStr() c++

by O_x 2022. 7. 7.
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

 

'LeetCode' 카테고리의 다른 글

125. Valid Palindrome 문제  (0) 2022.07.10
796. Rotate String 문제  (0) 2022.07.07
1. Two Sum Leetcode 문제  (0) 2022.07.04
287. Find the Duplicate Number c++ 문제 풀이  (0) 2022.07.03
581. Shortest Unsorted Continuous Subarray c++ 문제  (0) 2022.06.23

댓글