码迷,mamicode.com
首页 > 其他好文 > 详细

792. Number of Matching Subsequences

时间:2018-05-03 00:59:44      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:vector   roc   bsp   ==   lookup   AC   sub   iss   ret   

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

标签:vector   roc   bsp   ==   lookup   AC   sub   iss   ret   

原文地址:https://www.cnblogs.com/JTechRoad/p/8983249.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!