题目描述:
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
.
思路是这样的:
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;
}
};