30. 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).

解决该问题的关键是理解清楚要求。
给定一个目标字符串s,一个单词集合words。
要求使得words集合中所有元素连续出现在s中的首位置组成的集合(元素顺序不考虑)。

正如所给实例,目标字符串s: “barfoothefoobarman”
对比单词集合words: [“foo”, “bar”]
我们发现,在pos=0 ~ 5时“barfoo”恰好匹配,则0压入结果vector;
在pos=9 ~ 14时“foobar”恰好匹配,则9压入结果vector;

vector<int> findSubstring(string s, vector<string>& words) {
    if (words.empty())return vector<int>();

    vector<int> res;
    unordered_map<string, int> word_cnt;

    for (auto x : words)word_cnt[x]++;

    int word_size = words[0].size();
    int word_nums = words.size();
    int s_size = s.size();

    int i = 0, j = 0;
    int len = s_size - word_size * word_nums + 1;
    for (i = 0; i < len; i++){
        unordered_map<string, int> temp_count;
        for (j = 0; j < word_nums; j++){
            string word = s.substr(i + j * word_size, word_size);
            if (word_cnt.find(word) != word_cnt.end()){
                ++temp_count[word];
                if (temp_count[word] > word_cnt[word])break;
            }
            else break;
        }
        if (j == word_nums)res.push_back(i);
    }
    return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值