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.
Subscribe to see which companies asked this question.
題目
給出字符串S和字符串T,計(jì)算S的不同的子序列中T出現(xiàn)的個(gè)數(shù)。
子序列字符串是原始字符串通過刪除一些(或零個(gè))產(chǎn)生的一個(gè)新的字符串,并且對剩下的字符的相對位置沒有影響。(比如,“ACE”是“ABCDE”的子序列字符串,而“AEC”不是)。
樣例
給出S = "rabbbit", T = "rabbit"
返回 3
分析
利用動(dòng)態(tài)規(guī)劃去做,我們用dp[i][j]表示S與T的前i個(gè)字符與前j個(gè)字符的匹配子串個(gè)數(shù)。可以知道:
1)初始條件:T為空字符串時(shí),S為任意字符串都能匹配一次,所以dp[i][0]=1;S為空字符串,T不為空時(shí),不能匹配,所以dp[0]j=0。
2)若S的第i個(gè)字符等于T的第j個(gè)字符時(shí),我們有兩種匹配的選擇:其一,若S的i-1字符匹配T的j-1字符,我們可以選擇S的i字符與T的j字符匹配;其二,若S的i-1字符子串已經(jīng)能與T的j字符匹配,放棄S的i字符與T的j字符。因此這個(gè)情況下,dp[i][j]=dp[i-1][j-1]+dp[i-1][j]。
3)若S的第i個(gè)字符不等于T的第j個(gè)字符時(shí),這時(shí)只有當(dāng)S的i-1字符子串已經(jīng)能與T的j字符匹配,該子串能夠匹配。因此這個(gè)情況下,dp[i][j]=dp[i-1][j]。
代碼
public class Solution {
/**
* @param S, T: Two string.
* @return: Count the number of distinct subsequences
*/
public int numDistinct(String S, String T) {
// write your code here
if (S == null || T == null) {
return 0;
}
int[][] nums = new int[S.length() + 1][T.length() + 1];
for (int i = 0; i <= S.length(); i++) {
nums[i][0] = 1;
}
for (int i = 1; i <= S.length(); i++) {
for (int j = 1; j <= T.length(); j++) {
nums[i][j] = nums[i-1][j];
if (S.charAt(i - 1) == T.charAt(j - 1)) {
nums[i][j] += nums[i - 1][j - 1];
}
}
}
return nums[S.length()][T.length()];
}
}