首页 > 其他 > 详细

Distinct Subsequences

时间:2014-03-23 20:11:24      阅读:468      评论:0      收藏:0      [点我收藏+]

题目原型:

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.

基本思路:

根据递推式 t[i][j] = t[i][j-1] + (S[i]==T[j])?t[i-1][j-1]:0(i字符串T的下标,j是字符串S的下标)得出。

	public int numDistinct(String S, String T)
	{
		int[][] num = new int[T.length()+1][S.length()+1];
		//初始化边缘条件
		for(int i = 0;i<S.length();i++)
			num[0][i] = 0;
		for(int i = 0;i<T.length();i++)
			num[i][0] = 0;
		
		for(int indexS = 1;indexS<=S.length();indexS++)
		{
			for(int indexT = 1;indexT<=indexS&&indexT<=T.length();indexT++)
			{
				if(S.charAt(indexS-1)==T.charAt(indexT-1))
				{
					//当T的长度为1时
					if(indexT==1)
						num[indexT][indexS] = num[indexT][indexS-1]+1;
					else
						num[indexT][indexS] = num[indexT][indexS-1]+num[indexT-1][indexS-1];
				}
				else
					num[indexT][indexS] = num[indexT][indexS-1];
			}
		}
		return num[T.length()][S.length()];
	}



Distinct Subsequences,布布扣,bubuko.com

Distinct Subsequences

原文:http://blog.csdn.net/cow__sky/article/details/21879905

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!