28. Implement strStr()
Problem
Input: haystack = "hello", needle = "ll"
Output: 2Input: haystack = "aaaaa", needle = "bba"
Output: -1Analysis
Code
Last updated
Input: haystack = "hello", needle = "ll"
Output: 2Input: haystack = "aaaaa", needle = "bba"
Output: -1Last updated
class Solution {
fun strStr(haystack: String, needle: String): Int {
if (needle.isEmpty()) {
return 0
}
val charIndex = IntArray(256)
charIndex.fill(-1)
for (i in needle.indices) {
charIndex[needle[i].toInt()] = i
}
var index = 0
val len = haystack.length - needle.length
var hi: Int
var ni: Int
while (index <= len) {
hi = index
ni = 0
while (hi < haystack.length && ni < needle.length && haystack[hi] == needle[ni]) {
hi++
ni++
}
when {
ni == needle.length -> return index
index >= len -> return -1
else -> index += (needle.length - charIndex[haystack[index + needle.length].toInt()])
}
}
return -1
}
}