天题系列: 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.

 

这题的dp解法要先看基础点的

Interleaving String

public class Solution {
    public int numDistinct(String s, String t) {
        if(s==null||s.length()<t.length()) return 0;
        int[][] dp = new int[s.length()+1][t.length()+1];
        dp[0][0] = 1;
        for(int i=1;i<=s.length();i++){
            dp[i][0] = 1; // t is empty, matches whatever s is
        }
        for(int j=1;j<=t.length();j++){
            dp[0][j] = 0; // s is empty, nothing in t can match 
        }
        for(int i=1;i<=s.length();i++){
            for(int j=1; j<=t.length();j++){
                //注意这个位置是第i位置,第j位,dp和s,t的位置序号不一致!
                // if t is already matched or not within s.subarray(0,i)
                // consider if t is still within s.subarray(0,i+1), actually determined by without i
                // e.g.: s[rato], t[rat]
                dp[i][j] = dp[i-1][j];
                if(s.charAt(i-1)==t.charAt(j-1)){
                    // in this situation, originally mismatched t[rat'b'], due to the addition of 'b' to s[ratk...b], now it is determined by both minus 1 character "b"
                    dp[i][j] += dp[i-1][j-1];
                }
            }
        }
        return dp[s.length()][t.length()];
    }
}

BM 解法

基础

Boyer-Moore: Implement strStr() --- find a needle in a haystack

但是这道题我反正理解不了

public class Solution {
   public int numDistinct(String S, String T) {
        int[] occurence = new int[T.length() + 1];
        occurence[0] = 1;
        for(int i = 0; i < S.length(); i++){
            for(int j = T.length() - 1; j >= 0 ; j--)
                if(S.charAt(i) == T.charAt(j)){
                    if(occurence[j] > 0)
                        occurence[j + 1] += occurence[j];
                }
        }
        return occurence[T.length()];
    }
}

 

posted @ 2015-06-10 07:26  世界到处都是小星星  阅读(141)  评论(0编辑  收藏  举报