Skip to content

Commit 9408c9e

Browse files
committed
添加0028.实现strStr Go语言版本
1 parent ff2ec86 commit 9408c9e

File tree

1 file changed

+89
-1
lines changed

1 file changed

+89
-1
lines changed

problems/0028.实现strStr.md

Lines changed: 89 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -726,10 +726,98 @@ class Solution:
726726

727727
Go:
728728

729+
```go
730+
// 方法一:前缀表使用减1实现
731+
732+
// getNext 构造前缀表next
733+
// params:
734+
// next 前缀表数组
735+
// s 模式串
736+
func getNext(next []int, s string) {
737+
j := -1 // j表示 最长相等前后缀长度
738+
next[0] = j
739+
740+
for i := 1; i < len(s); i++ {
741+
for j >= 0 && s[i] != s[j+1] {
742+
j = next[j] // 回退前一位
743+
}
744+
if s[i] == s[j+1] {
745+
j++
746+
}
747+
next[i] = j // next[i]是i(包括i)之前的最长相等前后缀长度
748+
}
749+
}
750+
func strStr(haystack string, needle string) int {
751+
if len(needle) == 0 {
752+
return 0
753+
}
754+
next := make([]int, len(needle))
755+
getNext(next, needle)
756+
j := -1 // 模式串的起始位置 next为-1 因此也为-1
757+
for i := 0; i < len(haystack); i++ {
758+
for j >= 0 && haystack[i] != needle[j+1] {
759+
j = next[j] // 寻找下一个匹配点
760+
}
761+
if haystack[i] == needle[j+1] {
762+
j++
763+
}
764+
if j == len(needle)-1 { // j指向了模式串的末尾
765+
return i - len(needle) + 1
766+
}
767+
}
768+
return -1
769+
}
770+
```
771+
772+
```go
773+
// 方法二: 前缀表无减一或者右移
774+
775+
// getNext 构造前缀表next
776+
// params:
777+
// next 前缀表数组
778+
// s 模式串
779+
func getNext(next []int, s string) {
780+
j := 0
781+
next[0] = j
782+
for i := 1; i < len(s); i++ {
783+
for j > 0 && s[i] != s[j] {
784+
j = next[j-1]
785+
}
786+
if s[i] == s[j] {
787+
j++
788+
}
789+
next[i] = j
790+
}
791+
}
792+
func strStr(haystack string, needle string) int {
793+
n := len(needle)
794+
if n == 0 {
795+
return 0
796+
}
797+
j := 0
798+
next := make([]int, n)
799+
getNext(next, needle)
800+
for i := 0; i < len(haystack); i++ {
801+
for j > 0 && haystack[i] != needle[j] {
802+
j = next[j-1] // 回退到j的前一位
803+
}
804+
if haystack[i] == needle[j] {
805+
j++
806+
}
807+
if j == n {
808+
return i - n + 1
809+
}
810+
}
811+
return -1
812+
}
813+
```
814+
815+
816+
729817

730818

731819
-----------------------
732820
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
733821
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
734822
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
735-
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
823+
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>

0 commit comments

Comments
 (0)