392判断子序列
cpp
复制代码
class Solution {
public:
bool isSubsequence(string s, string t)
{
vector<vector<int>>dp(s.size()+1,vector<int>(t.size()+1,0));
int res=0;
for (int i = 1; i <= s.size(); i++)
{
for(int j=1;j<=t.size();j++)
{
if(s[i-1]==t[j-1]) dp[i][j]=dp[i-1][j-1]+1;
else dp[i][j]=dp[i][j-1];
res=res>dp[i][j]?res:dp[i][j];
}
}
if(res == s.size()) return true;
return false;
}
};
792匹配子序列的单词书
cpp
复制代码
class Solution {
public:
int numMatchingSubseq(string s, vector<string>& words)
{
vector<vector<int>> index(256);
for(int i=0;i<s.size();i++)
{
char c=s[i];
index[c].push_back(i);
}
int res=0;
for (string word : words)
{
int i = 0;
int cur = -1;
for (; i < word.size(); i++)
{
char c = word[i];
if (index[c].empty())
{
break;
}
auto it = upper_bound(index[c].begin(), index[c].end(), cur);
if (it == index[c].end()) {
break;
}
// 向前移动指针 j
cur = *it;
}
// 如果 word 完成匹配,则是子序列
if (i == word.size()) {
res++;
}
}
return res;
}
};
115不同的子序列
cpp
复制代码
class Solution {
public:
int numDistinct(string s, string t) {
vector<vector<uint64_t>> dp(s.size() + 1, vector<uint64_t>(t.size() + 1));
for (int i = 0; i < s.size(); i++) dp[i][0] = 1;
for (int j = 1; j < t.size(); j++) dp[0][j] = 0;
for (int i = 1; i <= s.size(); i++)
{
for (int j = 1; j <= t.size(); j++)
{
if (s[i - 1] == t[j - 1])
{
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
}
else {
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[s.size()][t.size()];
}
};