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,求t在s中子串的个数(注意是非连续的)
思路:用dp(i,j)表示字符串t[1..j]在s[1..i]中出现的子串的个数,其状态转移方程为
如果s[i]==t[j],有dp(i,j)=dp(i-1,j-1)+dp(i-1,j)
如果s[i]不等于t[j],有dp(i,j)=dp(i-1,j)
注意初始值为dp[0..len(s)][0] = 1,而dp[0][1..len(t)] = 0
代码如下:
public class Solution
{
public int numDistinct(String s, String t)
{
int len1 = s.length(), len2 = t.length();
int[][] dp = new int[len1 + 1][len2 + 1];
dp[0][0] = 1;
for (int i = 0; i < len2; i++)
{
dp[0][i + 1] = 0;
}
for (int i = 0; i < len1; i++)
{
dp[i + 1][0] = 1;
}
for (int i = 0; i < len1; i++)
{
for (int j = 0; j < len2; j++)
{
if (s.charAt(i) == t.charAt(j))
{
dp[i + 1][j + 1] = dp[i][j] + dp[i][j + 1];
}
else
{
dp[i + 1][j + 1] = dp[i][j + 1];
}
}
}
return dp[len1][len2];
}
}
动态规划的滚动数组实现如下:
public class Solution
{
public int numDistinct(String s, String t)
{
int len1 = s.length(), len2 = t.length();
int[][] dp = new int[2][len2 + 1];
dp[0][0] = 1;
for (int i = 0; i <= len1; i++)
{
for (int j = 0; j <= len2; j++)
{
if (i == 0 && j > 0) {
dp[i & 1][j] = 0;
} else if (i > 0 && j == 0) {
dp[i & 1][j] = 1;
} else if (i > 0 && j > 0) {
if (s.charAt(i - 1) == t.charAt(j - 1)) {
dp[i & 1][j] = dp[(i - 1) & 1][j] + dp[(i - 1) & 1][j - 1];
} else {
dp[i & 1][j] = dp[(i - 1) & 1][j];
}
}
}
}
return dp[len1 & 1][len2];
}
}