개발 일지
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해주었습니다.
'코딩 테스트 > LeetCode' 카테고리의 다른 글
46. Permutations (두 개의 정렬된 리스트 병합) (0) | 2024.06.13 |
---|---|
46. Permutations (순열) (0) | 2024.04.08 |
59. Spiral Matrix II (나선형 매트릭스 II) (0) | 2024.03.20 |
27. Remove Element (요소 제거) (0) | 2024.03.19 |
1337. The K Weakest Rows in a Matrix (행렬에서 가장 약한 K 행) (0) | 2023.11.03 |