入门力扣自学笔记201 C++ (题目编号:792)

792. 匹配子序列的单词数

题目:

给定字符串 s 和字符串数组 words, 返回  words[i] 中是s的子序列的单词个数 。

字符串的 子序列 是从原始字符串中生成的新字符串,可以从中删去一些字符(可以是none),而不改变其余字符的相对顺序。

例如, “ace” 是 “abcde” 的子序列。


示例 1:

输入: s = "abcde", words = ["a","bb","acd","ace"]
输出: 3
解释: 有三个是 s 的子序列的单词: "a", "acd", "ace"。


Example 2:

输入: s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"]
输出: 2


提示:

1 <= s.length <= 5 * 104
1 <= words.length <= 5000
1 <= words[i].length <= 50
words[i]和 s 都只由小写字母组成。


来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/number-of-matching-subsequences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


思路:

首先,建立两个set容器,来存储遍历过得字符串,一旦出现重复的字符串,就可以不同重新便利了。

其次,遍历每一个words中的字符串,跟s进行比对,如果最后words中的字符串遍历后等于原来长度,那么这个就是子序列,反之,不是子序列。

最后,根据ans的结果,返回ans即可。


代码:

class Solution {
public:
    int numMatchingSubseq(string s, vector<string>& words) {
        int ans = 0;
        unordered_set<string> pass;
        unordered_set<string> fail;
        for(string w : words)
        {
            if(pass.count(w))
            {
                ans ++ ;
                continue;
            }
            if(fail.count(w))
                continue;
            int sl = 0;
            int wl = 0;
            while(sl < s.size() && wl < w.size())
            {
                if(s[sl] == w[wl])
                {
                    sl++;
                    wl++;
                }
                else
                    sl++;
            }
            if(wl == w.size())
            {
                ans++;
                if(!pass.count(w))
                    pass.insert(w);
            }
            else
            {
                if(!fail.count(w))
                    fail.insert(w);
            }
        }
        return ans;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值