leetcode 字符串匹配

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].
题目大意:判断words中有多少字符串是S的子集,输出是S子集的个数
解题思路:遍历求子集+去重,开始没去重,最后几个样例就超时了,我的去重思路是每次遍历过的字符串用vis做访问记录,如果这个字符串是S的子集,再用map做是子集记录,如果下一次遍历遇到的字符串之前遍历过,如果它是子集,count++,否则就跳过此次循环。
AC代码如下:

class Solution {
public:
    int numMatchingSubseq(string S, vector<string>& words) {
        unordered_map<string, int> map;//是子集,map值++
        unordered_map<string, bool>vis;//之前遍历过的vis值为true
        int count = 0;
        for(int i = 0;  i < words.size(); ++i){
            int s = 0, w = 0;
            if(vis[words[i]] && map[words[i]] == 0)
                continue;
            while (s < S.size() && w < words[i].size() && map[words[i]] == 0) {
                if(words[i][w] == S[s]){
                    s++;
                    w++;
                }
                else
                    s++;
            }
            if(map[words[i]] > 0){
                count++;
            }
            if(w >= words[i].size()){
   //         cout<<"words[i] = "<<words[i]<<endl;
                map[words[i]]++;
                count++;
            }
            vis[words[i]] = true;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值