LeetCode 30. Substring with Concatenation of All Words

本文介绍了解决LeetCode上子串拼接问题的方法,采用滑动窗口算法结合哈希表来高效处理字符串匹配。文章详细展示了如何统计目标字符串出现次数,并在主字符串中寻找符合条件的所有子串。

问题

https://leetcode.com/problems/substring-with-concatenation-of-all-words/

解法

经过测试,words中的字符串存在重复的情况。
因此第一步是统计每种字符串个数。
然后在s中进行枚举,比较当前串是否符合。
在枚举s时使用滑动窗口算法。

typedef unordered_map<string, int>::iterator it;
class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int> ret;
        if (words.size() < 1)
            return ret;
        int wdLen = words[0].size();
        if (s.size() <wdLen* words.size())
            return ret;
        unordered_map<string, int> wdCnt;
        for(int i=0; i< words.size(); ++i)
            wdCnt[words[i]]++;
        for (int i=0; i<wdLen; ++i)
        {
            int left = i;
            unordered_map<string, int> found;
            int foundNum = 0;
            for(int j = i; j + wdLen<=s.size(); j+= wdLen)
            {
                string sub = s.substr(j, wdLen);
                if(wdCnt.find(sub) == wdCnt.end())
                {
                    found.clear();
                    foundNum =0;
                    left = j+wdLen;
                }else{
                    found[sub]++;
                    foundNum++;
                    if (found[sub] > wdCnt[sub])
                    {
                        while(found[sub] > wdCnt[sub])
                        {
                            string ss = s.substr(left, wdLen);
                            found[ss]--;
                            foundNum--;
                            left+= wdLen;
                        }
                    }

                    if (foundNum == words.size())
                    {
                        ret.push_back(left);
                        string ss = s.substr(left, wdLen);
                        found[ss]--;
                        foundNum--;
                        left+=wdLen;
                    }
                }
            }
        }
        return ret;

    }
};

实现细节

unordered_map<> clear()

Clear content
All the elements in the unordered_map container are dropped: their destructors are called, and they are removed from the container, leaving it with a size of 0.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值