Wednesday, March 20, 2013

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.


let f_ij be the number of distinct subsequences of T[0,j] in S[0,i], then
f_i+1,j = S[i+1] == T[j] ? f_{i,j-1} + f_{i,j} : f_{i,j}


public class Solution {
    public int numDistinct(String S, String T) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(S.length() ==0 ) return 0;
        assert T.length() >0;
       
        int[] dp = new int[T.length()];
        for(int i = 0; i < dp.length; i++) dp[i] = 0;
       
        for(int i =0 ; i < S.length() ; i++){
            for(int j = T.length()-1; j>=0; j--){
                if(T.charAt(j) == S.charAt(i)){
                    dp[j] += j>0 ? dp[j-1] : 1;
                }
            }
        }
        return dp[T.length()-1];
    }
}

No comments:

Post a Comment

Manacher's Longest Palindromic Substring Algorithm

http://manacher-viz.s3-website-us-east-1.amazonaws.com/#/