No.162 - LeetCode792 - 字符串子序列匹配(下标挂链二分)

本文介绍了一种使用二分查找优化的子序列匹配算法,通过预处理字符串S的字符位置,加速了对words列表中每个单词是否为S的子序列的判断。算法首先建立一个二维向量,存储S中每个字符的所有位置,然后对于words中的每个单词,利用二分查找确定其字符在S中的相对位置,从而高效判断该单词是否为S的子序列。
class Solution {
public:
    int bsearch(int L,int R,vector<int>& V,int key){
        //printf("<%d %d %d>\n",L,R,key);
        if(L+1>=R) return R;
        int mid = (L+R)/2;
        if(V[mid] <= key) return bsearch(mid,R,V,key);
        return bsearch(L,mid,V,key);
    }
    int numMatchingSubseq(string S, vector<string>& words) {
        vector<vector<int>> V(26,vector<int>(0));
        for(int i=0;i<26;i++) V[i].push_back(-1);
        for(int i=0;i<S.length();i++){
            V[S[i]-'a'].push_back(i);
        }
        int ans = 0;
        for(int i=0;i<words.size();i++){
            int lastloc = -1;
            bool flag = true;
            //cout<<words[i]<<endl;
            for(int j=0;j<words[i].length();j++){
                int index = words[i][j]-'a';
                int nowloc = bsearch(0,V[index].size(),V[index],lastloc);
                if(nowloc == V[index].size()){
                    flag = false;
                    break;
                }
                lastloc = V[index][nowloc];
            }
            if(flag) ans++;
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值