Substring with Concatenation of All Words

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

For example, given:
s: “barfoothefoobarman”
words: [“foo”, “bar”]

You should return the indices: [0,9].
(order does not matter).
思路:类似于Minimum Window Substring,但是又有不同,本题目中可行解必须包含字典中所有的words,不能包含其他的words。
步骤:
(1)以步长为字典中len(words)遍历字符串s,同时遍历时起始位置为[0, len(words)),start记录当前窗口的起始位置
(2)每一次遍历时,构造查找哈希表find,记录每个words出现的次数,如果words在dict中,(1)出现的次数小于dict中该words出现的次数时find[words]++,count++(记录匹配words的个数),(2)出现的次数大于dict中该words出现的次数时,找到start到当前位置,words第一次出现的位置,index,for words in [start,index],find[words]–,count–;同时start = index + len(words);
如果words不在dict中,count = 0;start = currentindex + len(words);find.clear();
(3)如果count == size(dict),表示找到一个有限的substring,此时 find[currentwords]–;start += len(words); count –;
(4)重复(1)(2)(3),直到找到所有的index,代码如下:

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words){
        map<string, int>srcWords;
        int size = words.size();
        for(int i = 0; i < size; ++i)
            srcWords[words[i]]++;
        int lenw = words[0].length(), start = 0, lens = s.length(), count = 0;
        vector<int> ret;
        for(int i = 0; i < lenw; ++i){
            map<string, int> find;
            start = i;
            count = 0;
            for(int j = i; j <= lens - lenw;j += lenw){
                string tmp = s.substr(j, lenw);
                if(srcWords[tmp]){//tmp 在字典中
                    find[tmp]++;
                    count ++;
                    if(find[tmp] > srcWords[tmp]){//当前单词出现的次数超过字典中该单词出现的次数
                        int indexTmp;
                        for(int k = j-lenw; k >= start; k -= lenw){
                            if(tmp == s.substr(k, lenw))
                                indexTmp = k;
                        }
                        for(int k = indexTmp; k >= start; k -= lenw){
                            string tmp = s.substr(k, lenw);
                            find[tmp]--;
                            count --;
                        }
                        start = indexTmp + lenw;
                    }
                }
                else{
                    count = 0;
                    start = j + lenw;
                    find.clear();
                }
                if(count == size){//找到
                    ret.push_back(start);
                    string tmp = s.substr(start, lenw);
                    find[tmp]--;
                    start += lenw;
                    count --;
                }
            }
        }
        return ret;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值