当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢

关于论青少年尽早学少儿编程之说

Kubernetes: (4) Common commands

解析掌握现代化少儿编程实操能力

带你刷(牛客网)C语言百题(第四天)

叶酸&适配体修饰DNA纳米载体|CdS纳米颗粒修饰DNA|科研试剂

数据可视化----网页显示温湿度

Verilog的时间格式系统任务----$printtimescale、$timeformat

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

一线技术人应该关注的四种思维能力

Common power symbols meaning sharing
随机推荐
Samba服务器配置(什么情况下需要服务器)
怎么实现您的个人知识库?
scratch 编程 + 小学数学
The difference between analog, digital and switching
siRNA-S-S-PEG-LMWP|M-MSN-siRNA介孔二氧化硅修饰RNA(齐岳RNA功能化修饰)
Related phrases include usage and collocation (include)
用 Array.every & Array.some 匹配全部/部分内容 es6
百度实习学弟深夜吐槽:原来大厂是这种生活啊
微博账号奇葩逻辑产品设计
MSNs-SS-siRNA二氧化硅-二硫键-核酸RNA|HA-SS-siRNA,hyaluronic acid透明质酸修饰RNA(RNA修饰剂)
根据昵称首字母生成头像
C语言学习书籍(提高篇)
Mass data query scheme mysql_Mysql massive data storage and solution 2 - Mysql sub-table query massive data... [easy to understand]
Samba server configuration (when a server is required)
webUI测试框架设计思路详解
[mathematical foundation] probability and mathematical statistics related concept learning
一线技术人应该关注的四种思维能力
Unity判断字符串是否可以转为float类型
图床软件要收费,算了我自己写一个开源免费的。
Safe Browser will have these hidden features that will let you play around with your browser