leetcode 30: Substring with Concatenation of All Words

I did this problem again today and tried a more efficient way. The runtime is reduced more than 10 times (32ms now). The idea is also using two unordered map to count the number of different words. But the loop now is different.

I use the start variable to loop just for the length of one word. And from this start, I check the whole string after to see if it contains a concatenation. The second loop is like a moving window.

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int> res;
        if(s.empty()||words.empty())
            return res;
        int slen=s.length();
        int wordLen=words[0].length();
        int wordNum=words.size();
        for(int i=0;i<wordNum;i++)
            dict[words[i]]++;//initialize the dictionary for words
        for(int start=0;start<wordLen;start++)
        {
            int i=start,j=start;
            int count=0;
            while(i<=slen-wordLen*wordNum&&j<=slen-wordLen)
            {
                auto it=dict.find(s.substr(j,wordLen));
                if(it==dict.end())//this word is not in the dict, clear everything
                {
                    count=0;
                    curr_table.clear();
                    i=j+wordLen;
                }
                else
                {
                    curr_table[it->first]++;
                    count++;
                    while(curr_table[it->first]>it->second)
                    {
                        string temp=s.substr(i,wordLen);
                        curr_table[temp]--;
                        count--;
                        i+=wordLen;
                    }
                    if(count==wordNum)
                        res.push_back(i);
                }
                j+=wordLen;
            }
            curr_table.clear();
        }
        return res;
    }
private:
    unordered_map<string,int> dict,curr_table;
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值