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"
Return 3
.
Code in Java:
public class Solution {
public int numDistinct(String S, String T) {
//count the number of ways to convert S to T by deleting some characters in S.
if(S.length()==0&&T.length()==0) return 0;
if(S.length()<T.length()) return 0;
int lenS = S.length(), lenT = T.length();
//Use opj[i][j] to represent the number of ways to convert S[0...i-1] to T[0...j-1]
//So opj[lenS][lenT] is the total number of ways to convert S to T
int[][] opj = new int[lenS+1][lenT+1];
//opj[i][0] represents the number of ways to convert S[0...i-1] to an empty string
//so for any string, there is only one ways, which is deleting all the characters
for(int i=0; i<lenS+1; i++)
opj[i][0]=1;
//There are two possibilities when computing opj[i][j] from S[0...i-1] to T[0...j-1]:
//if S[i-1]==T[j-1], we can obtain opj[i][j] by either remaining or deleting S[i-1]
// if remain S[i-1]: opj[i][j]=opj[i-1][j-1]
// the number of ways from S[0...i-1] to T[0...j-1]=the number of ways
// from S[0...i-2] to T[0...j-2]
// if delete S[i-1]: opj[i][j]=opj[i-1][j]
// the number of ways from S[0...i-1] to T[0...j-1]=the number of ways
// from S[0...i-2] to T[0...j-1]
//if S[i-1]!=T[j-1], there is only one way to obtain opj[i][j], wo we have
// opj[i][j] = opj[i-1][j]
// the number of ways from S[0...i-1] to T[0...j-1]=the nubmer of ways from
// S[0...i-2] to T[0...j-1]
for(int i=1; i<lenS+1; i++){
for(int j=1; j<lenT+1&&j<=i; j++){
opj[i][j] = S.charAt(i-1)==T.charAt(j-1)?opj[i-1][j-1]:0;
if(i-1>=j) opj[i][j]+= opj[i-1][j];
}
}
return opj[lenS][lenT];
}
}