2021-11-25:给定两个字符串s1和s2,返回在s1中有多少个子串等于s2。来自美团。

2021-11-25:给定两个字符串s1和s2,返回在s1中有多少个子串等于s2。来自美团。

答案2021-11-25:

改写kmp算法。
next数组多求一位。
比如:str2 = aaaa,
那么,next = -1,0,1,2,3。
最后一个3表示,终止位置之前的字符串最长前缀和最长后缀的匹配长度。
也就是next数组补一位。
时间复杂度:O((N)。
空间复杂度:O(N)。

代码用golang编写。代码如下:

package main

import "fmt"

func main() {
    str1 := "aaaab"
    str2 := "aaa"
    ret := sa(str1, str2)
    fmt.Println(ret)
}

func sa(s1, s2 string) int {
    if len(s1) < len(s2) {
        return 0
    }
    str1 := []byte(s1)
    str2 := []byte(s2)
    return count(str1, str2)
}

// 改写kmp为这道题需要的功能
func count(str1 []byte, str2 []byte) int {
    x := 0
    y := 0
    count := 0
    next := getNextArray(str2)
    for x < len(str1) {
        if str1[x] == str2[y] {
            x++
            y++
            if y == len(str2) {
                count++
                y = next[y]
            }
        } else if next[y] == -1 {
            x++
        } else {
            y = next[y]
        }
    }
    return count
}

// next数组多求一位
// 比如:str2 = aaaa
// 那么,next = -1,0,1,2,3
// 最后一个3表示,终止位置之前的字符串最长前缀和最长后缀的匹配长度
// 也就是next数组补一位
func getNextArray(str2 []byte) []int {
    if len(str2) == 1 {
        return []int{-1, 0}
    }
    next := make([]int, len(str2)+1)
    next[0] = -1
    next[1] = 0
    i := 2
    cn := 0
    for i < len(next) {
        if str2[i-1] == str2[cn] {
            cn++
            next[i] = cn
            i++
        } else if cn > 0 {
            cn = next[cn]
        } else {
            next[i] = 0
            i++
        }
    }
    return next
}

执行结果如下:
图片


左神java代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

福大大架构师每日一题

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值