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:

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


给出字符串S和一系列字符串words,求出words中为S的子序列的个数。如果简单的对words中每一个字符串进行判断,时间复杂度会比较高(过不过没试过),于是想着先对S进行处理,求出S中每个位置的下一个字母(a-z)的位置。这样对words中的每一个字符串,根据求得的位置信息跳转即可。


代码:

class Char {
public:
    Char() {
        for(int i = 0; i < 26; ++i) {
            next[i] = INT_MAX;
        }
    }
    int get(char c) {
        return next[c - 'a'];
    }
    void set(char c, int n) {
        next[c - 'a'] = n;
    }
    void assign(const Char& c) {
        for(int i = 0; i < 26; ++i) {
            next[i] = c.next[i];
        }
    }
    int next[26];
};

class Solution {
public:
    int numMatchingSubseq(string S, vector<string>& words) {
        vector<Char> chars(S.size() + 1);
        Char pos;
        for(int i = S.size()-1; i >= 0; --i) {
            chars[i+1].assign(pos);
            pos.set(S[i], i+1);
        }
        chars[0].assign(pos);

        int result = 0;
        for(auto word : words) {
            bool flg = true;
            int next = 0;
            for(int i = 0; i < word.size(); ++i)  {
                next = chars[next].get(word[i]);
                if(next == INT_MAX) {
                    flg = false;
                    break;
                }
            }
            if(flg) {
                ++result;
            }
        }
        return result;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值