LeetCode #792 - Number of Matching Subsequences

本文介绍了一种高效的算法,用于解决给定字符串S和一系列单词,判断这些单词是否为S的子序列的问题。通过构建字母下标哈希表,利用二分查找优化匹配过程,实现快速计数匹配单词的数量。

题目描述:

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].

class Solution {
public:
    int numMatchingSubseq(string S, vector<string>& words) {
        int count=0;
        vector<vector<int>> hash(26); //表示每个字母所对应的所有下标
        for(int i=0;i<S.size();i++)
            hash[S[i]-'a'].push_back(i);
        for(auto word:words)
        {
            int i=-1; //令i等于-1的目的是让第一次匹配一定能找得到
            bool flag=true;
            for(auto c:word)
            {
                //i是上一次匹配的下标,当前的匹配从i之后开始
                //一定要用upper_bound,因为它是找第一个大于i的数,所以可以避免重复
                auto it=upper_bound(hash[c-'a'].begin(),hash[c-'a'].end(),i);
                if(it==hash[c-'a'].end())
                { //c需要在hash[c-'a']中找一个大于i的下标来匹配,如果找不到说明匹配完了
                    flag=false;
                    break;
                }
                //i表示接下来要从word的哪一个下标开始查找,也就是说S[i]之前的子序列已经匹配掉了
                else i=*it; //令i等于上一次匹配的下标
            }
            if(flag) count++;
        }
        return count;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值