(leetcode)Distinct Subsequences
来源:互联网 发布:尼古丁 知乎 编辑:程序博客网 时间:2024/05/03 10:44
问题描述:
Given a string S and a string T, count the number of distinct subsequences ofT in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie,"ACE"
is a subsequence of "ABCDE"
while "AEC"
is not).
Here is an example:
S = "rabbbit"
, T = "rabbit"
Return 3
.
问题分析:
只可以用删除字符的方法从第一个字符串变换到第二个字符串,求出一共有多少种变换方法。做多了就发现,又是一个动态规划的题。那就直接上二维数组d[][]:
dp[i][j]表示:T的前j个字符在S的前i个字符中出现的次数。
1)初始条件:T为空字符串时,S为任意字符串都能匹配一次(只能一一删除),所以dp[i][0]=1;S为空字符串,S不为空时,不能匹配,所以dp[0][j](j>1)=0(空串怎么可能通过删除变成其他非空串?!)。
2)若S的第i个字符等于T的第j个字符时,我们有两种匹配的选择:其一,我们可以选择S的i字符与T的j字符匹配,我保留我S的第i个字符,这就看S的前i-1个字符串与T的j-1个字符串匹配的次数;其二,放弃S的第i字符,我倒要看看我S的前i-1个字符能与你T的前j个字符匹配多少次。因此这个情况下,dp[i][j]=dp[i-1][j-1]+dp[i-1][j]。
3)若S的第i个字符不等于T的第j个字符时,这时只有当S的i-1字符子串已经能与T的j字符匹配,反正S的第i个字符与T的第j个字符不匹配了,对于S中前i的字符串与Td的前j的字符串来说,前者的最后一个字符不能匹配后者的最后的一个字符,所以是没用的,我只能看前i-1个字符能与你前j个字符匹配的次数。因此这个情况下,dp[i][j]=dp[i-1][j]。
public int numDistinct(String S, String T) { if(S==null||T==null||S.length()<=0){ return 0; }if(T.length()<=0)return 1; int slen = S.length(); int tlen = T.length(); int dp[][]=new int[slen+1][tlen+1]; //边界初始化 for(int i=0;i<=tlen;i++){ dp[0][i]=0; } for(int i=0;i<=slen;i++){ dp[i][0]=1; } for(int i=1;i<=slen;i++){ for(int j=1;j<=tlen;j++){ //不等情况 if(S.charAt(i-1) != T.charAt(j-1)){ dp[i][j]=dp[i-1][j]; }else{ //相等情况 dp[i][j]=dp[i-1][j-1]+dp[i-1][j]; } } } return dp[slen][tlen];}
0 0
- LeetCode Distinct Subsequences
- [LeetCode]Distinct Subsequences
- [Leetcode] Distinct Subsequences *
- [leetcode] Distinct Subsequences
- [LeetCode] Distinct Subsequences
- [Leetcode] Distinct Subsequences
- leetcode 111: Distinct Subsequences
- LeetCode Distinct Subsequences
- [leetcode] Distinct Subsequences
- LeetCode - Distinct Subsequences
- Leetcode:Distinct Subsequences
- [LeetCode]Distinct Subsequences
- [LeetCode] Distinct Subsequences
- [Leetcode]Distinct Subsequences
- [leetcode]Distinct Subsequences
- Leetcode: Distinct Subsequences
- Leetcode: Distinct Subsequences
- [leetcode] Distinct Subsequences
- 如何单独编译Android源代码中的模块
- list分区表转化为list-list组合分区表的测试过程
- VBS基础篇 - 变量(2) - 命名规则
- MFC工程加入控制台调试信息输出
- 从yarn中获取mapreduce job信息的api
- (leetcode)Distinct Subsequences
- Xcode自行更新资源文件
- 指针
- SQLite集成与用法
- java多线程:创建与启动
- mysql使用中问题记录
- 重置应用程序偏好
- POJ1523 SPF 【求割点Tarjan】
- 一个程序员的书单