前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >2021-08-15:给定一个字符串Str,返回Str的所有子序列中有多少不同的字面值。

2021-08-15:给定一个字符串Str,返回Str的所有子序列中有多少不同的字面值。

作者头像
福大大架构师每日一题
发布2021-09-03 15:23:22
4440
发布2021-09-03 15:23:22
举报

2021-08-15:给定一个字符串Str,返回Str的所有子序列中有多少不同的字面值。

福大大 答案2021-08-15:

返回值=上+新-修正。

时间复杂度:O(N)

空间复杂度:O(N)。

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

代码语言:javascript
复制
package main

import "fmt"

func main() {
    s := "aabb"
    ret := distinctSubseqII(s)
    fmt.Println(ret)
}

func distinctSubseqII(s string) int {
    if len(s) == 0 {
        return 0
    }
    m := 1000000007

    count := make([]int, 26)
    all := 1 // 算空集
    for _, x := range s {
        add := (all - count[x-'a'] + m) % m
        all = (all + add) % m
        count[x-'a'] = (count[x-'a'] + add) % m
    }
    return all - 1
}

func zuo(s string) int {
    if len(s) == 0 {
        return 0
    }
    m := 1000000007
    map0 := make(map[byte]int)
    all := 1 // 一个字符也没遍历的时候,有空集
    for i := 0; i < len(s); i++ {
        x := s[i]
        newAdd := all
        curAll := all
        curAll = (curAll + newAdd) % m
        if _, ok := map0[x]; ok {
            curAll = (curAll - map0[x] + m) % m
        } else {
            curAll = (curAll + m) % m
        }
        all = curAll
        map0[x] = newAdd
    }
    return all
}

执行结果如下:

***

[左神java代码](https://github.com/algorithmzuo/coding-for-great-offer/blob/main/src/class17/Code05_DistinctSubseqValue.java)

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-08-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 福大大架构师每日一题 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档