792. Number of Matching Subsequences**

本文介绍了解决LeetCode 792题目的方法,该题要求找出字典中作为给定字符串S的子序列的单词数量。通过使用vector记录S中每个字符的索引,并利用upper_bound函数快速判断单词是否为S的子序列,从而实现高效求解。

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

792. Number of Matching Subsequences**

https://leetcode.com/problems/number-of-matching-subsequences/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].

C++ 实现 1

这道题需要更快的判断 wordS 的子序列.

方法是: 使用 vector<vector<int>> record 用于记录 S 中每个字符的索引, 比如 S = "abac", 那么 record 就是 {{0, 2}, {1}, {3}}, 分别表示 S[i] 的索引. 之后对于 word 中的每个字符 word[i], 要求它下一个字符 word[i + 1]S 中的索引, 必须大于 word[i]S 中的索引. 换句话说, 就是 word[i]word[i + 1] 都要出现在 S 中, 并且 word[i + 1] 要出现在 word[i] 之后. 现在的问题是这句话换成代码如何实现? 下面的代码使用 upper_bound 实现了.

class Solution {
private:
    vector<vector<int>> record;
    bool isSubsequence(const string &word) {
        int x = -1;
        for (auto &c : word) {
            auto it = std::upper_bound(record[c - 'a'].begin(),
                                      record[c - 'a'].end(),
                                      x);
            if (it == record[c - 'a'].end()) return false;
            x = *it;
        }
        return true;
    }
public:
    int numMatchingSubseq(string S, vector<string>& words) {
        int count = 0;
        record = vector<vector<int>>(26);
        for (int i = 0; i < S.size(); ++i) record[S[i] - 'a'].push_back(i);
        for (auto &word : words)
            if (isSubsequence(word))
                count ++;
        return count;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值