792. Number of Matching Subsequences

 

 参考代码: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;
    }
};

 

posted @ 2019-08-05 13:32  有梦就要去实现他  阅读(127)  评论(0编辑  收藏  举报