题目

Given a string S and a string T, count the number of distinct subsequences of T 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"

Return3.

思路

1. 初始化一个矩阵number[i][j]用来记录字符串T的前j个字符出现在字符串S的前i个字符的次数,当j=0时,令number[i][j]=1;

2. 当S的第i个字符与T的第j个字符不同时,则说明S的第i个字符对number[i][j]没有影响,即number[i][j]=number[i-1][j];

3. 当S的第i个字符与T的第j个字符不同时,则说明S的第i个字符对number[i][j]有影响,number[i][j]除了要算上原来的number[i-1][j],还要算上新的可能性,即number[i-1][j-1].

例子

  0 r a b b i t
0 1 0 0 0 0 0 0
r 1 1 0 0 0 0 0
a 1 1 1 0 0 0 0
b 1 1 1 1 0 0 0
b 1 1 1 2 1 0 0
b 1 1 1 3 3 0 0
i 1 1 1 3 3 3 0
t 1 1 1 3 3 3 3

代码

     public static int result(String str1, String str2){
int len1 = str1.length(), len2 = str2.length();
int[][] res = new int[len1+1][len2+1];
for(int i=0;i<len1+1;i++){
res[i][0] = 1;
}
for(int i=1;i<len1+1;i++){
for(int j=1;j<len2+1;j++){
if(str1.charAt(i-1)!=str2.charAt(j-1))
res[i][j] = res[i-1][j];
else
res[i][j] = res[i-1][j]+res[i-1][j-1];
} }
return res[len1][len2];
}

最新文章

  1. linux
  2. linux云服务器mysql ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock’
  3. C ~ 链式队列与循环队列
  4. SQL Server(三)——增、删、改、查
  5. ubuntu 出现g++ : Depends: g++-4.8 (&gt;= 4.8.2-5~) but it is not going to be installed
  6. sql boolean类型
  7. poj3050
  8. Lintcode: Subarray Sum Closest
  9. php源码编译常见错误解决方案
  10. web服务器 应用 服务器
  11. 数据同步DataX
  12. [置顶] EasyMock的简单使用
  13. Java多线程--让主线程等待所有子线程执行完毕
  14. nodejs集成sqlite
  15. 小白的Python之路 day1 字符编码
  16. Python 3.6.3 利用 Dlib 19.7 和 opencv 实现人脸68点定位 进行人脸识别
  17. Device tree customization
  18. redis 集群搭建碰到的问题
  19. JS(JavaScript)的初了解5(更新中&#183;&#183;&#183;)
  20. linux位数查看

热门文章

  1. 设计模式学习笔记——Composite 组合模式
  2. es之IK分词器
  3. jetty 启动时出现的问题
  4. Tarjan算法整理
  5. qbzt day7上午
  6. fatal: repository &#39;xxxx&#39; not found
  7. 阶段1 语言基础+高级_1-3-Java语言高级_1-常用API_1_第6节 static静态_15_静态代码块
  8. AWK之随心所欲-高手篇
  9. Far and away the best prize that life has given to us is the chance to work hard at work worth doing
  10. TensorFlow学习笔记5-概率与信息论