您的位置:首页 > 产品设计 > UI/UE

Distinct Subsequences

2015-08-25 08:58 513 查看
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.

思路:题目的意思是给定一个字符串S,删除其中某些字符,使之变成字符串T,问共有几种方法。

设d[i][j]表示的是字符串S中的第1个字符到第i个字符,变换成T字符串中的第1个字符到第j个字符,所有的方法总数。接下来列公式,目前头脑中要想到d[i][j]跟什么有关呢? 如果说当前S已经遍历到i,而T已经遍历到j,判断S[i]是否与T[j]相等?

如果S[i]==T[j] , 说明d[i][j]=d[i-1][j]+d[i-1][j-1] ,其意思是当可以从S的前i-1个字符变换到T的前j个字符的时候,这个时候既然已经可以由前i-1个字符变换成T的前j个字符了,那么i可以直接删除了;或者已经可以由S得前i-1个字符变换成T的前j-1个字符时,那么要变成T的前j个字符,那么在S中要将第i个字符保留。

如果S[i]!=T[j] ,那么说明对于T中 的第一个字符到第j个字符,S中i字符是没有用的,把它删除即可。 d[i][j]=d[i-1][j];

初始条件:

d[0][0] =1 空串变成空串,只有一种方法

d[i][0]=1 将一个字符串变换为空串也只有一种方法

d[0][j]=0 如果S为空串,当然不可能变成T

注: S和T的下标都是从0开始的,而d[i][j]表示的S的前i个字符变成T的前j个字符,所有要知道,当d[i][j]中i表示的是S的第i个字符时,要判断的S[i-1]与T[i-1]是否相等。

public class Solution {
public int numDistinct(String s, String t) {
int m=s.length();
int n=t.length();
if(m<n) return 0;
int[][] d=new int[m+1][n+1];
d[0][0]=1;
for(int i=1;i<=m;i++)
d[i][0]=1;
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
if(s.charAt(i-1)==t.charAt(j-1))
d[i][j]=d[i-1][j-1]+d[i-1][j];
else d[i][j]=d[i-1][j];
}
}

return d[m]
;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: