加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

792. Number of Matching Subsequences

发布时间:2020-12-16 10:47:23 所属栏目:百科 来源:网络整理
导读:? ?参考代码:https://leetcode.com/problems/number-of-matching-subsequences/discuss/117575/C++-12-Line-Solution-with-Explanation ? 思路:把每个S的字符的下标存储下来,同一个单词存储多个位置。然后每个单词进行遍历,每次寻找对应字符最小的下标,

?

?参考代码:https://leetcode.com/problems/number-of-matching-subsequences/discuss/117575/C++-12-Line-Solution-with-Explanation

?

思路:把每个S的字符的下标存储下来,同一个单词存储多个位置。然后每个单词进行遍历,每次寻找对应字符最小的下标,这样后面的字符的下标必须大于前一个字符的下标,如果找不到就说明没有子序列。使用upper_bound找第一个大于当前索引的值

比如S为"abbac",找bac是否在里面,找到第一个b之后,继续找a,但是这个时候只能使用index=3的a,而不能使用index=0的啊

class Solution {
public:
    int numMatchingSubseq(string S,vector<string>& words) {
        vector<vector<int>> indexs(26);
        for(int i = 0;i < S.size();i++)
            indexs[S[i] - a].push_back(i);
        int res = 0;
        for(string word : words){
            bool found = true;
            int index = -1;
            for(char tmp : word){
                auto it = upper_bound(indexs[tmp - a].begin(),indexs[tmp - a].end(),index);
                if(it == indexs[tmp - a].end())
                    found = false;
                else
                    index = *it;
            }
            if(found)
                res++;
        }
        return res;
    }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读