首页 > 代码库 > Distinct Subsequences
Distinct Subsequences
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
.
答案
public class Solution { int[][] matrix; boolean []equals; String S; String T; int lenS; int lenT; private int calDistinct(int i, int j) { if (matrix[i][j] != -1) { return matrix[i][j]; } if (lenS - i == lenT - j) { matrix[i][j] = equals[j]? 1 : 0; return matrix[i][j]; } if (lenS - i < lenT - j) { matrix[i][j] = 0; return matrix[i][j]; } matrix[i][j] = 0; if (S.charAt(i) == T.charAt(j)) { if (j + 1 == lenT) { matrix[i][j] += 1; } else { matrix[i][j] += calDistinct(i + 1, j + 1); } } for(int p=i+1;p<lenS;p++) { if(S.charAt(p)==T.charAt(j)) { matrix[i][j] += calDistinct(p, j); break; } } return matrix[i][j]; } public int numDistinct(String S, String T) { if (S == null || T == null || S.length() < T.length()) { return 0; } if (T.length() == 0) { return 1; } if (S.length() == 0) { return 0; } this.S = S; this.T = T; this.lenS = S.length(); this.lenT = T.length(); matrix = new int[lenS][lenT]; for (int i = 0; i < lenS; i++ ) { for (int j = 0; j < lenT; j++ ) { matrix[i][j] = -1; } } equals=new boolean[lenT]; equals[lenT-1]=S.charAt(lenS-1)==T.charAt(lenT-1); int p; for(p=lenT-2;p>=0;p--) { equals[p]=equals[p+1]&&S.charAt(lenS-(lenT-p))==T.charAt(p); } return calDistinct(0, 0); } }
Distinct Subsequences
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。