distinct subsequences

Given a string S and a string T, count the number of distinct subsequences of S which equals T.

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相等的子串的个数

看到字符串子序列或者配准类问题,要考虑到是否可以使用动态规划。。对于配准类,两个字符串,一般使用二维数组。dp[i][j]表示s字符串的前i个字符组成的字符串,它的所有子串中与t的前j个字符组成的字符串相等的个数。
初始化:当j=0时,t字符串为空,那么i为任意值,它构成的字符串中只有一个空串和t相等,此时dp[i][0]=1.
当i=0时,j!=0时,s为空串,t不为空串,dp为0.
递推公式:当s的第i个字符与t的第j个字符相等时,dp[i][j]=dp[i-1][j-1]+dp[i-1][j](前i-1个字符的子串中与j个t字符串相等的个数)。当他们不相等时,dp[i][j]=dp[i-1][j],就只能是s的前i-1个的字符串中含有j个t字符的字符串了

 

class Solution {
    public int numDistinct(String s, String t) {
        if(s.length()<t.length()) return 0;
        //dp[i][j]表示s的前i个字符构成的字符串的子串与t的j个字符构成的字符串相等的个数
        int[][] dp=new int[s.length()+1][t.length()+1];
        //初始化,当j=0时,也就是t为空串时,i无论为何值,都只有一个空子串与t相等.当i=0时,j=0时为1,j!=0时,都为0.
        for(int i=0;i<s.length()+1;i++) dp[i][0]=1;
        
        for(int i=1;i<=s.length();i++)
            for(int j=1;j<=t.length();j++){
                if(s.charAt(i-1)==t.charAt(j-1)){
                    dp[i][j]=dp[i-1][j-1]+dp[i-1][j];
                }else{
                    dp[i][j]=dp[i-1][j];
                }
            }
        
        return dp[s.length()][t.length()];
    }
}

 

posted on 2018-01-22 15:53  夜的第八章  阅读(110)  评论(0编辑  收藏  举报

导航