代码随想录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()];
    }
};
相关推荐
gfdhy5 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
百***06015 小时前
SpringMVC 请求参数接收
前端·javascript·算法
weixin_457760005 小时前
Python 数据结构
数据结构·windows·python
一个不知名程序员www6 小时前
算法学习入门---vector(C++)
c++·算法
云飞云共享云桌面6 小时前
无需配置传统电脑——智能装备工厂10个SolidWorks共享一台工作站
运维·服务器·前端·网络·算法·电脑
明洞日记6 小时前
【数据结构手册002】动态数组vector - 连续内存的艺术与科学
开发语言·数据结构·c++
福尔摩斯张6 小时前
《C 语言指针从入门到精通:全面笔记 + 实战习题深度解析》(超详细)
linux·运维·服务器·c语言·开发语言·c++·算法
fashion 道格6 小时前
数据结构实战:深入理解队列的链式结构与实现
c语言·数据结构
橘颂TA6 小时前
【剑斩OFFER】算法的暴力美学——两整数之和
算法·leetcode·职场和发展
Dream it possible!7 小时前
LeetCode 面试经典 150_二叉搜索树_二叉搜索树的最小绝对差(85_530_C++_简单)
c++·leetcode·面试