[leetcode] 792. Number of Matching Subsequences

本文详细解析了如何使用C++和STL中的upper_bound函数解决LeetCode 792题:给定字符串S和字典words,找出字典中作为S子序列的单词数量。文章通过实例解释了算法步骤,包括利用26位数组存储S中每个字符的索引,以及如何应用二分查找判断单词是否为子序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S.

Example :
Input:

S = "abcde"
words = ["a", "bb", "acd", "ace"]

Output:

3

Explanation:

There are three words in words that are a subsequence of S: "a", "acd", "ace".

Note:

  • All words in words and S will only consists of lowercase letters.
  • The length of S will be in the range of [1, 50000].
  • The length of words will be in the range of [1, 5000].
  • The length of words[i] will be in the range of [1, 50].

分析

题目的意思是:给定字典words,和一个字符串S,问字典中有多少个字符串是S的字串。

  • 用一个26位的数组alpha存储S种每个字符的索引。然后对于words,用二分法查找每个word中每个字符c的索引是否存在,如果二分查找找到了尾部,说明索引不存在,则这个单词就不是S的substring。
  • upper_bound(a.begin(),a.end(),x)返回的是迭代器

代码

class Solution {
public:
    int numMatchingSubseq(string S, vector<string>& words) {
        vector<vector<int>> alpha(26);
        for(int i=0;i<S.size();i++){
            alpha[S[i]-'a'].push_back(i);
        }
        int res=0;
        for(auto word:words){
            int x=-1;
            bool found=true;
            for(char c:word){
                auto it=upper_bound(alpha[c-'a'].begin(),alpha[c-'a'].end(),x);
                if(it==alpha[c-'a'].end()){
                    found=false;
                    break;
                }else{
                    x=*it;
                }
            }
            if(found){
                res++;
            }
        }
        return res;
    }
};

参考文献

792. Number of Matching Subsequences
C++STL中的upper_bound()函数的使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值