1. 程式人生 > >792. Number of Matching Subsequences

792. Number of Matching Subsequences

true als public cto AC RoCE const ber str

Brute force (time out)

class Solution {
public:
    int numMatchingSubseq(string S, vector<string>& words) {
        int res = 0;
        for (const auto& w : words)
            if (isSubseq(S, w))
                res++;
        return res;
    }
    bool isSubseq(const string &S, const
string &w) { int i = 0, j = 0, m = S.length(), n = w.length(); while (i < m && j < n) { if (S[i] == w[j]) { i++; j++; } else { i++; } } return j == n; } };

Preprocess S:

class Solution {
public:
    int numMatchingSubseq(string S, vector<string>& words) {
        vector<vector<int>> lookup(26);
        for (int i = 0; i < S.length(); i++)
            lookup[S[i]-a].push_back(i);
        
        int res = 0;
        for (const
auto& w : words) if (isSubseq(lookup, w)) res++; return res; } bool isSubseq(const vector<vector<int>>& lookup, const string &w) { for (int l = 0, i = 0, n = w.length(); i < n; i++) { const auto &look = lookup[w[i] - a]; auto it = lower_bound(look.begin(), look.end(), l); if (it == look.end()) return false; l = *it + 1; } return true; } };

792. Number of Matching Subsequences