28.找出字符串中第一个匹配项的下标
练习次数 **
https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/
- 找出字符串中第一个匹配项的下标 简单 │ 2269 │ 44.0% 的 2.6M
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 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
- haystack 和 needle 仅由小写英文字符组成
// @leet start
func strStr(haystack string, needle string) int {
if len(needle) > len(haystack) {
return -1
}
if len(needle) <= 0 {
return -1
}
harSS := []rune(haystack)
neSS := []rune(needle)
for idx, v := range harSS {
p := neSS[0]
if v != p {
continue
}
if idx > len(harSS)-len(neSS) {
break
}
tmpH := idx
tmpN := 0
for tmpH < len(harSS) && tmpN < len(neSS) {
if harSS[tmpH] != neSS[tmpN] {
break
}
tmpH++
tmpN++
}
if tmpN == len(neSS) {
return idx
}
}
return -1
}
// @leet end
解法2
// @leet start
func strStr(haystack string, needle string) int {
total := []rune(needle + "#" + haystack)
m := len(needle)
pi := make([]int, len(total))
for i := 1; i < len(total); i++ {
l := pi[i-1]
for l > 0 && total[l] != total[i] {
l = pi[l-1]
}
if total[l] == total[i] {
pi[i] = l + 1
if pi[i] == m {
return i - m*2
}
}
}
return -1
}
// @leet end