LeetCode - The World's Leading Online Programming Learning Platform
1 <= haystack.length, needle.length <= 104
haystack
and needle
consist of only lowercase English characters.문자열의 길이가 짧기 때문에 왠만하면 통과된다.
indexOf()
의 기능과 동일하게 때문에 해당 메소드를 사용하여 통과 → Sol1
indexOf를 직접 구현하여 통과 → Sol2
indexOf()
class Solution {
fun strStr(haystack: String, needle: String): Int {
return haystack.indexOf(needle)
}
}
문자열의 순회하며 직접 비교
→ indexOf()
구현
class Solution {
fun strStr(haystack: String, needle: String): Int {
var idx = 0
while (idx <= haystack.length - needle.length) {
var cnt = 0
for (i in needle.indices) {
if (haystack[idx + i] == needle[i]) cnt++
else break
}
if (cnt == needle.length) return idx
else idx++
}
return -1
}
}