【题目】
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
.
题意:给定两个字符串S和T,返回S中有多少个子序列和T一样。
思路:动态规划。本来想用一个一维数组来存储结果,花好久时间没弄出来,还是用二维数组写起来更清楚容易。直接看代码吧,注释应该还算比较清楚。
public class Solution {
public int numDistinct(String S, String T) {
if (S == null || T == null) return 0;
if (S.equals("") || T.equals("")) return 0;
//table[i][j]表示S[0~i]中有多少个T[0~j]的个数
int[][] table = new int[S.length()][T.length()];
//给table第一行赋值,意思是S[0]中有多少个T[0~j]
//显然,S[0]最多包含一个T[0],故table[0][1~n]都为0
if (S.charAt(0) == T.charAt(0)) {
table[0][0] = 1;
}
for (int i = 1; i < S.length(); i++) {
char s = S.charAt(i);
//给table[i][0]赋值,意思是S[0~i]中有多少个T[0]
if (s == T.charAt(0)) {
table[i][0] = table[i - 1][0] + 1;
} else {
table[i][0] = table[i - 1][0];
}
for (int j = 1; j < T.length(); j++) {
char t = T.charAt(j);
if (s == t) {
//如果用S[i]匹配T[j],那么S[0~i-1]中共有table[i-1][j-1]个T[0~j-1]
//如果不用S[i]匹配T[i],那么S[0~i]中共有table[i-1][j]个T[0~j]
table[i][j] = table[i - 1][j - 1] + table[i - 1][j];
} else {
//S[i]!=T[j]时,S[0~i]中共有table[i-1][j]个T[0~j]
table[i][j] = table[i - 1][j];
}
}
}
return table[S.length() - 1][T.length() - 1];
}
}