Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags
more
Archives
Today
Total
관리 메뉴

개발 일지

28. Find the Index of the First Occurrence in a String (문자열에서 첫 번째 발생 인덱스 찾기) 본문

코딩 테스트/LeetCode

28. Find the Index of the First Occurrence in a String (문자열에서 첫 번째 발생 인덱스 찾기)

포카리tea 2024. 3. 21. 16:37

두 개의 문자열 needle과 haystack가 주어지면 haystack에서 needle이 처음 발생한 인덱스를 반환하거나, needle이 건haystack의 일부가 아닌 경우 -1을 반환합니다.

예시 1:

입력: haystack = "sadbutsad", needle = "sad"
출력: 0
설명: "sad"는 인덱스 0과 6에서 발생합니다 
첫 번째 발생은 인덱스 0이므로 0을 반환합니다.

 

예시 2:

입력: haystack = "leetcode", needle = "leeto"
출력: -1
설명: "leeto"는 "leetcode"에 포함되지 않았으므로 -1을 반환합니다.

 

 

조건:

  • 1 <= haystack.length, needle.length <= 10^4
  • haystackneedle영문 소문자로만 구성됩니다.

 

정답:

public class Solution 
{
    public int StrStr(string haystack, string needle) 
    {
        return haystack.IndexOf(needle); 
    }
}

해설:  indexOf를 이용하여 해당 문자열의 위치를 발견하여 return해주었습니다.