792. Number of Matching Subsequences

792. Number of Matching Subsequences


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:

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

方法1:

思路:

brute force的方法最高50 * 5000 * 50000的复杂度,需要优化。string s的位置信息被重复使用,只需要hash所有char的index就可以。每次查找时记录上一个字母找到的位置prev,下一个位置不能低于prev。这里用binary search的内置函数upper_bound找到第一个大于prev + 1的index,如果没找到,可以直接break。

这里运用到了找subsequence的经典子函数。

Complexity

Time complexity: O(S + W * L * log(S))
Space complexity: O(S)

S: length of S
W: number of words
L: length of a word


class Solution {
public:
    int numMatchingSubseq(string S, vector<string>& words) {
        unordered_map<char, vector<int>> hash;
        int res = 0;
        for (int i = 0; i < S.size(); i++) hash[S[i]].push_back(i);
        for (string word: words) {
            int prev = -1, i = 0;
            for (; i < word.size(); i++) {
                if (!hash.count(word[i])) break;
                auto it = upper_bound(hash[word[i]].begin(), hash[word[i]].end(), prev);
                if (it == hash[word[i]].end()) break;
                prev = *it;
            }
            if (i == word.size()) res++;
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值