代码随想录day55

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()];
    }
};
相关推荐
laplace01239 分钟前
浮点数精度
人工智能·算法·agent·qwen
blackicexs15 分钟前
第四周第五天
数据结构·算法
重生之后端学习17 分钟前
98. 验证二叉搜索树
java·数据结构·后端·算法·职场和发展
菜鸡儿齐21 分钟前
leetcode-移动零
数据结构·算法·leetcode
紫陌涵光39 分钟前
54. 替换数字(第八期模拟笔试)
数据结构·c++·算法
TracyCoder12340 分钟前
LeetCode Hot100(53/100)——739. 每日温度
算法·leetcode·职场和发展
_Twink1e41 分钟前
[算法竞赛]二、链表
数据结构·算法·链表
民乐团扒谱机1 小时前
【读论文】引力与惯性的起源:从全息原理到牛顿定律与爱因斯坦方程
算法·量子力学··万有引力·爱因斯坦方程·全息原理·牛顿定律
努力学算法的蒟蒻1 小时前
day84(2.13)——leetcode面试经典150
算法·leetcode·面试
@––––––1 小时前
力扣hot100—系列8-回溯算法
javascript·算法·leetcode