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.

这一题使用DR来做最简洁。 如果用burust的方法也行,但是时间复杂度很高。。。。

n(T.length())

m(S.length())

[m,n] 表示在S的前m个字符里, T的前n个字符组成的字符串的出现次数。

故:[m,n] = [m -1, n] + [m-1,n-1]a,  (a = 1 if(S.charAt(m) == T.charAt(n)).

然后还需要判断一下test case。

 1 public class Solution {
 2     public int numDistinct(String S, String T) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         if(T.length() == 0 || S.length() == 0) return 0;
 6         
 7         int[][] map = new int[S.length()][T.length()];
 8         map[0][0] = (S.charAt(0) == T.charAt(0)) ? 1 : 0;
 9         int count = 0;
10         for(int i = 0; i < S.length(); i ++){
11             if(S.charAt(i) == T.charAt(0)) count ++;
12             map[i][0] = count;
13         }
14         
15         for(int i = 1; i < T.length(); i ++){
16             for(int j = 1; j < S.length(); j ++){
17                 map[j][i] = map[j-1][i];
18                 if(S.charAt(j) == T.charAt(i)){
19                     map[j][i] += map[j-1][i-1];
20                 }
21             }
22         }
23         return map[S.length()-1][T.length()-1];
24     }
25 }

 

posted on 2013-09-12 11:57  Step-BY-Step  阅读(199)  评论(0编辑  收藏  举报

导航