LeetCode-30 Substring with Concatenation of All Words

本文介绍了一种使用滑动窗口法解决字符串匹配问题的方法,通过定义一个可变大小的窗口,在给定字符串中查找所有由指定字符串数组组成子字符串的起点。

题目:给定一个字符串S,一个定长度n的字符串数组words[],在S中找出所有由words拼接而成的子字符串的起点。

思路:类似于最大不重复子字符串,定义一个滑动窗口,每次窗口走n个字符,判断是否匹配words中的某个字符串

class Solution {
public:

//滑窗法,维护一个左右边界可变的窗口,若模式串单词长度为n,则只需进行n次窗口滑动。
//假设某次匹配,窗口内的字符串和S相同,则计数加1, 窗口左边界向右移动n个长度,右边界继续滑动,
//若滑动后单词不能匹配,则左边界变为左边界+n,
//若滑动后单词匹配成功但次数超过S中字符的数目,则左边界持续移动n,直到排除一个相同的字符,然后右边界继续滑动。
    vector<int> findSubstring(string S, vector<string> &L) {
        vector<int> ans;
        int n = S.size(), cnt = L.size();
        if (n <= 0 || cnt <= 0) return ans;

        // init word occurence
        unordered_map<string, int> dict;
        for (int i = 0; i < cnt; ++i) dict[L[i]]++;

        // travel all sub string combinations
        int wl = L[0].size();
        for (int i = 0; i < wl; ++i) {
            int left = i, count = 0;
            unordered_map<string, int> tdict;
            for (int j = i; j <= n - wl; j += wl) {
                string str = S.substr(j, wl);
                // a valid word, accumulate results
                if (dict.count(str)) {
                    tdict[str]++;
                    if (tdict[str] <= dict[str]) 
                        count++;
                    else {
                        // a more word, advance the window left side possiablly
                        while (tdict[str] > dict[str]) {
                            string str1 = S.substr(left, wl);
                            tdict[str1]--;
                            if (tdict[str1] < dict[str1]) count--;
                            left += wl;
                        }
                    }
                    // come to a result
                    if (count == cnt) {
                        ans.push_back(left);
                        // advance one word
                        tdict[S.substr(left, wl)]--;
                        count--;
                        left += wl;
                    }
                }
                // not a valid word, reset all vars
                else {
                    tdict.clear();
                    count = 0;
                    left = j + wl;
                }
            }
        }

        return ans;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值