2014年4月24日 星期四

[LeetCode] Distinct Subsequences

Problem:
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.
Solution:O(m*n)
public class Solution {
   public int numDistinct(String S, String T) {
      if (S==null||S.length()==0||T==null || T.length()==0 || S.length()<T.length()){
         return 0;
      }        
      
      int[][] nums=new int[T.length()+1][S.length()+1];
      for (int col=0; col<nums[0].length; col++){
         nums[0][col]=1;
      }
      
      for (int row=1; row<nums.length; row++){
         for (int col=1; col<nums[0].length; col++){
            nums[row][col]=nums[row][col-1];
            if (S.charAt(col-1)==T.charAt(row-1)){
               nums[row][col]+=nums[row-1][col-1];
            }
         }
      }     
      return nums[T.length()][S.length()];
   }
}

沒有留言:

張貼留言