[leetcode]792. Number of Matching Subsequences

162 篇文章 0 订阅
53 篇文章 0 订阅

[leetcode]792. Number of Matching Subsequences


Analysis

明天就是除夕啦—— [每天刷题并不难0.0]

Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S.
在这里插入图片描述

Explanation:

递归~

Implement

最开始试图用map标记每个单词中字符出现的次数,然后与S比较,但是发现这样的话会忽略字符出现的顺序,心塞

class Solution {
public:
    int numMatchingSubseq(string S, vector<string>& words) {
        unordered_map<char, int> mmp;
        for(auto c:S){
            if(mmp.find(c) != mmp.end())
                mmp[c]++;
            else
                mmp[c] = 1;
        }
        int len = words.size();
        int cnt = 0;
        for(int i=0; i<len; i++){
            unordered_map<char, int> mmp1;
            for(auto c:words[i]){
                if(mmp1.find(c) != mmp1.end())
                    mmp1[c]++;
                else
                    mmp1[c] = 1;
            }
            bool flag = true;
            for(auto it:mmp1){
                if(mmp[it.first] < it.second){
                    flag = false;
                    break;
                }
            }
            if(flag)
                cnt++;
        }
        return cnt;
    }
};

explanation:
https://leetcode.com/problems/number-of-matching-subsequences/discuss/117634/Efficient-and-simple-go-through-words-in-parallel-with-explanation

class Solution {
public:
    int numMatchingSubseq(string S, vector<string>& words) {
        vector<pair<int, int>> wait[128];
        int len = words.size();
        for(int i=0; i<len; i++)
            wait[words[i][0]].emplace_back(i, 1);
        for(char c:S){
            auto tmp = wait[c];
            wait[c].clear();
            for(auto it:tmp)
                wait[words[it.first][it.second++]].push_back(it);
        }
        return wait[0].size();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值