xinyu04

导航

[Google] LeetCode 792 Number of Matching Subsequences

Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

  • For example, "ace" is a subsequence of "abcde".

Solution

直接暴力进行遍历(双指针)

点击查看代码
class Solution {
private:
    map<string,int> mp;
    int ans=0;
public:
    int numMatchingSubseq(string s, vector<string>& words) {
        int n = s.size();
        int m = words.size();
        for(int i=0;i<m;i++)mp[words[i]]++;
        for(auto ele:mp){
            string cur = ele.first;
            int p1=0, p2=0;
            while(p1<n && p2<cur.size()){
                if(s[p1]==cur[p2]){p1++;p2++;}
                else {p1++;}
            }
            if(p2==cur.size())ans+=ele.second;
        }
        return ans;
    }
};

posted on 2022-09-09 20:04  Blackzxy  阅读(11)  评论(0编辑  收藏  举报