leetcode#792. Number of Matching Subsequences

792. Number of Matching Subsequences

Problem Description

Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S.

Analysis and Solution

基本思路是对words中的每一个word检查是否为S的一个子序列。但是如果每次检查都要扫描一遍S的话时间复杂度太高,所以就想到把S中字母的位置存储起来提高效率。扫描一遍字符串S并建立一个字典,记录每一个字母出现的位置并按照升序排列。对每一个word,遍历word并查找字典中当前字母的出现位置并保持其相对位置不变。代码如下:

class Solution {
public:
    int numMatchingSubseq(string S, vector<string>& words) {
        // build the dictionary
        vector<vector<int>> pos(26);
        for (int i=0; i<S.size(); i++) {
            pos[S[i] - 'a'].push_back(i);
        }

        int count = 0;
        for (int i=0; i<words.size(); i++) {
            int j = 0, cur = -1;
            // iterate each letter in the word
            while (j != words[i].size()) {
                int k = 0;
                while (k != pos[words[i][j] - 'a'].size()) {
                    // keep the relative positions by greedy
                    if (pos[words[i][j] - 'a'][k] > cur) {
                        cur = pos[words[i][j] - 'a'][k];
                        break;
                    }
                    k++;
                }
                // when there is no match, break to prune
                if (k == pos[words[i][j] - 'a'].size()) {
                    break;
                }
                j++;
            }
            // the case every letter could be matched
            if (j == words[i].size()) count++;
        }
        return count;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值