zoukankan      html  css  js  c++  java
  • 792. Number of Matching Subsequences

    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;
        }
    };
  • 相关阅读:
    Java 多线程(四) 多线程访问成员变量与局部变量
    再一贴[亲爱的,我不小心怀孕了~!]
    寒铁沉香木出处
    时间格式
    测试
    有关裁缝的
    转贴
    各种贝壳产地
    捕捞资料
    矿木资料
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/8983249.html
Copyright © 2011-2022 走看看