当前位置:   article > 正文

30. Substring with Concatenation of All Words

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/252602
推荐阅读
相关标签
  

闽ICP备14008679号