Search This Blog

Monday, December 24, 2012

LeetCode:Distinct Subsequences

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) {
        // Start typing your Java solution below
        // DO NOT write main() function
        HashMap<Character,ArrayList<Integer>> map = new HashMap<Character,ArrayList<Integer>>();
        for(int i=0;i<T.length();i++){
            if(map.containsKey(T.charAt(i))){
                map.get(T.charAt(i)).add(i);
            }else{
                ArrayList<Integer> temp = new ArrayList<Integer>();
                temp.add(i);
                map.put(T.charAt(i),temp);
            }
        }
        
        int[] res = new int[T.length()+1];
        res[0]=1;
        
        for(int i=0;i<S.length();i++){
            char c = S.charAt(i);
            if(map.containsKey(c)){
                ArrayList<Integer> temp = map.get(c);
                int[] old = new int[temp.size()];
                for(int j=0;j<temp.size();j++)
                        old[j]=res[temp.get(j)];
                for(int j=0;j<temp.size();j++)
                        res[temp.get(j)+1]+=old[j];
            }
        }
        return res[T.length()];
    }
}

1 comment:

traceformula said...

I have a solution using less space:

public class Solution {
public int numDistinct(String s, String t) {
if(s == null || t == null || t.length() == 0) return 0;
int[] dp = new int[t.length()];

for(int i = 0; i=0; j–){
if(c == t.charAt(j)){
dp[j] = dp[j] + (j!=0?dp[j-1]: 1);
}
}
}
return dp[t.length()-1];
}
}
URL: http://traceformula.blogspot.com/2015/08/distinct-subsequences.html