Leetcode - Distinct Subsequences

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.

public class Solution {
    public int numDistinct(String s, String t) {
        if (s == null)
            return 0;
        if (t == null || t.length() == 0)
            return 1;
        if (s.length() == 0)
            return 0;
        int lenS = s.length();
        int lenT = t.length();
        int[][] dp = new int[2][lenT + 1];
        dp[0][0] = 1;
        int lastLenS = 0;
        int currLenS = 1;
        for (int i = 1; i <= lenS; i++) {
            currLenS = 1 - lastLenS;
            dp[currLenS][0] = 1;
            for (int j = 1; j <= lenT; j++) {
                dp[currLenS][j] = dp[lastLenS][j];
                if (s.charAt(i - 1) == t.charAt(j - 1))
                    dp[currLenS][j] += dp[lastLenS][j-1];
            }
            lastLenS = currLenS;
        }
        return dp[currLenS][lenT];
    }
    
    // dp[i][j] = dp[i - 1][j] + (s[i - 1] == t[j - 1] ? dp[i - 1][j - 1] : 0);
    // dp[i][j]表示s的前i字符构成的子串能匹配t中前j个字符构成的子串的子序列数
    // 不管s和t当前考察位置处的字符是否相等,dp[i][j]至少有dp[i-1][j]
    // 如果当前考察位置处两字符相等,则再加上dp[i-1][j-1]的数目
    public int numDistinct1(String s, String t) {
        if (s == null)
            return 0;
        if (t == null || t.length() == 0)
            return 1;
        if (s.length() == 0)
            return 0;
        int lenS = s.length();
        int lenT = t.length();
        int[][] dp = new int[lenS + 1][lenT + 1];
        dp[0][0] = 1;
        for (int i = 1; i <= lenS; i++) {
            dp[i][0] = 1;
            for (int j = 1; j <= lenT; j++) {
                dp[i][j] = dp[i - 1][j];
                if (s.charAt(i - 1) == t.charAt(j - 1))
                    dp[i][j] += dp[i - 1][j - 1];
            }
        }
        return dp[lenS][lenT];
    }
}

猜你喜欢

转载自likesky3.iteye.com/blog/2207808