【LeetCode】Distinct Subsequences

本文介绍了一种使用动态规划方法计算字符串T在S中不同子序列数量的算法。通过记录S中每个字符出现的位置并利用count数组进行计算,最终得出T在S中的子序列总数。

题目描述:

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中包含多少个不同的S,任意一个位置不同都算作一个不同的S。

思路是这样的:

1、检索一遍S中每个字符出现的位置,储存在map<char, vector<int>>里。

2、用count[i][j]来储存S[i]处出现的T[0:j]子串数。

3、动态规划,S[i]在T中出现的位置j,count[i][j]=count[i-1][j]+count[i-1][j-1],端点处单独处理。

代码如下:

class Solution {
public:
	int numDistinct(string S, string T) 
	{
		if (!T.length() || !S.length())
			return 0;
		int num(0);
		unordered_map<char, vector<int>> index = findChar(T);
		vector<int> count(T.length() - 1);
		for (int i = 0; i < S.length(); i++)
		{
			if (!index.count(S[i]))
				continue;
			vector<int> line = index[S[i]];
			for (int j = line.size() - 1; j >= 0; j--)
			{
				if (line[j] == T.size() - 1)
				{
					if (count.empty())
						num++;
					else
						num += count[count.size() - 1];
				}
				else
					count[line[j]] = (line[j] == 0) ? (count[0] + 1) : (count[line[j]] + count[line[j] - 1]);
			}
		}
		return num;
	}
	unordered_map<char, vector<int>> findChar(string s)
	{
		unordered_map<char, vector<int>> index;
		for (int i = 0; i < s.length(); i++)
		{
			if (!index.count(s[i]))
			{
				vector<int> line;
				index[s[i]] = line;
			}
			index[s[i]].push_back(i);
		}
		return index;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值