본문 바로가기
Problem solving/LeetCode

[LeetCode] 28. Find the Index of the First Occurrence in a String (C++)

by 겸 2023. 7. 3.

문제

needle과 haystack 두 개의 문자열이 주어졌을 때, haystack에서 가장 처음 나타난 needle의 인덱스 찾기.

없으면 -1을 리턴

생각할 것

string의 find를 이용하면 되지 않을까?

💡 string의 find함수

  • 문자열을 찾으면 해당 문자열의 시작 인덱스를 리턴
  • 찾지못한다면 -1을 리턴 

코드

class Solution {
public:
    int strStr(string haystack, string needle) {
        return haystack.find(needle);   
    }
};
반응형