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;
        }
    };
  • 相关阅读:
    C#如何连接wifi和指定IP
    3.4 小结
    3.3.4.5 起始与清除
    3.3.4.4 打印行
    3.3.4.3 设置字段分隔字符
    3.3.4.2 字段
    3.3.4.1 模式与操作
    3.3.4 使用 awk 重新编排字段
    3.3.3 使用 join 连接字段
    3.3.2 使用 cut 选定字段
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/8983249.html
Copyright © 2011-2022 走看看