当前位置:网站首页>940. 不同的子序列 II
940. 不同的子序列 II
2022-07-29 20:16:00 【小卢要刷力扣题】
前言
给定一个字符串 s,计算 s 的 不同非空子序列 的个数。因为结果可能很大,所以返回答案需要对 10^9 + 7 取余 。
字符串的 子序列 是经由原字符串删除一些(也可能不删除)字符但不改变剩余字符相对位置的一个新字符串。
例如,“ace” 是 “abcde” 的一个子序列,但 “aec” 不是
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/distinct-subsequences-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
没有重复字符的时候

新的子串为{1}
2到来,新加{2},{1,2}
3到来,数量是之前的2倍
{3},{1,3},{2,3},{1,2,3}
有重复字符的时候


第二个1到来,重复了{1},因此新增数量为1

第三个1来了,重复了2个

因此可以推出,假设之前出现的字母的数量为X=100;
那么当下一次出现相同字母的数量为
all=perAll(上一个位置的all)+newAll(如果不重复字母新增的数量)-X;
用一个数组存储26个字母结尾的字符串数量,
all加上之前的all,如果出现过相同的字母,就减去数组中的相同字母的数

来到b,all=2
空串和{b}
来到第一个c,newAll=2,all=4,记录c:2
来到第2个c,newAll=4,all=8
因为c有记录,因此all要减2,
代码
class Solution {
public int distinctSubseqII(String s) {
if (s == null || s.length() == 0) {
return 0;
}
char[] str=s.toCharArray();
int all=1;
int mod=1000000007;
int[] map=new int[26];
for(int i=0;i<str.length;i++){
int newAll=all;
int curAll=(all+newAll)%mod;
all=(curAll-map[str[i]-'a']+mod)%mod;
map[str[i]-'a']=newAll;
}
return all-1;
}
}
边栏推荐
- 尿素偶联Urea-siRNA Conjugates|Cyclodextrin-siRNA-β-CD环糊精修饰RNA核酸(解析说明)
- es6语法使用默认参数和解构
- Expert advice | How to formulate a growth strategy for survival in an economic downturn
- :class数组写法
- ESP8266-Arduino programming example-I2C device address scan
- 核壳二氧化钛纳米颗粒修饰DNA|二氢杨梅素修饰DNA药物|相关介绍
- In the past six months, I have done those things about the automatic return of the transaction link...
- 论文写作全攻略|一篇学术科研论文该怎么写
- RNA修饰质谱检测|dextran-siRNA 葡聚糖化学偶联DNA/RNA|siRNA-PLGA聚乳酸-羟基乙酸共聚物修饰核糖核酸
- Omni-channel e-commerce | How can well-known domestic cosmeceuticals seize the opportunity to achieve rapid growth?
猜你喜欢

JUC并发编程基础AQS

使用MD5加密后的字符串存密码安全吗?你不得不了解的Hash算法

这半年我做交易链路自动化回归的那些事儿...

Agile Organization | The path for enterprises to overcome the impact of the digital wave

Baidu internship students late night fun: originally giant is this kind of life

The ambition of glory: "high-end civilians" in a smart world

7 行代码搞崩溃 B 站,原因令人唏嘘!

正则表达式

Kubernetes:(四)常用命令

The second growth curve | The driving guide for corporate innovation to break through the stagnation dilemma
随机推荐
scratch 编程 + 小学数学
ds1302——斌哥51
【无标题】
4D Summary: 38 Knowledge Points of Distributed Systems
使用IDEA连接mysql
ACM学习书籍简介
Kotlin - 协程作用域 CoroutineScope、协程构建器 CoroutineBuilder、协程作用域函数 CoroutineScope Functiom
带你刷(牛客网)C语言百题(第四天)
Related phrases include usage and collocation (include)
如何优雅的自定义 ThreadPoolExecutor 线程池
Verilog的时间格式系统任务----$printtimescale、$timeformat
诺氟沙星-DNA复合物|半乳糖化脂质体-聚阳离子-DNA复合物|注意事项
核壳二氧化钛纳米颗粒修饰DNA|二氢杨梅素修饰DNA药物|相关介绍
图床软件要收费,算了我自己写一个开源免费的。
ESP8266-Arduino programming example-I2C device address scan
Agile Organization | The path for enterprises to overcome the impact of the digital wave
offsetwidth111[通俗易懂]
C language learning books zero-based introductory articles
论文写作全攻略|一篇学术科研论文该怎么写
Looking for a job - a chat with my cousin