[LeetCode/Kotlin]Easy - 28. Find the Index of the First Occurrence in a String
2023. 6. 30. 08:57ㆍLeetCode/Kotlin | Easy
728x90
반응형
Find the Index of the First Occurrence in a String - LeetCode
Can you solve this real interview question? Find the Index of the First Occurrence in a String - 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. Example 1: I
leetcode.com
문제
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.
Example 1:
Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.
Example 2:
Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.
Constraints:
- 1 <= haystack.length, needle.length <= 104
- haystack and needle consist of only lowercase English characters.
풀이
나의 풀이법
풀이 접근 과정
처음엔 정말 소스코드로 하나하나 비교하여 만들었다.
금방 풀긴 했지만 특정 케이스에서 예외 처리가 되지 않아 정답이 아니었다.
그런데 그냥 입력받은 글자가 포함된 인덱스만 리턴하면 되지 않는가?
생각이 도달하자마자 금방 끝났다.
easy는 easy인듯!
최종 소스코드
class Solution {
fun strStr(haystack: String, needle: String) = haystack.indexOf(needle)
}
728x90
반응형
'LeetCode > Kotlin | Easy' 카테고리의 다른 글
[LeetCode/Kotlin]Easy - 58. Length of Last Word (0) | 2023.06.30 |
---|---|
[LeetCode/Kotlin]Easy - 1356. Sort Integers by The Number of 1 Bits (0) | 2023.06.30 |
[LeetCode/Kotlin]Easy - 219. Contains Duplicate II (0) | 2023.06.30 |
[LeetCode/Kotlin]Easy - 136. Single Number (0) | 2023.06.30 |
[LeetCode/Kotlin]Easy - 169. Majority Element (0) | 2023.06.30 |