2017-09-19 LeetCode_030 Substring with Concatenation of All Words

来源:互联网 发布:免费网络推广渠道 编辑:程序博客网 时间:2024/05/17 20:27

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

solution:

class Solution {
2
public:
3
    vector<int> findSubstring(string s, vector<string>& words) {
4
        map<string, int> counts;
5
        for (int i = 0; i < words.size(); i++) counts[words[i]]++;
6
        int n = s.length(), num = words.size(), len = words[0].length();
7
        vector<int> indexes;
8
        for (int i = 0; i < n-num*len+1; i++) {
9
            map<string, int> seen;
10
            int j = 0;
11
            while (j < num) {
12
                string word = s.substr(i+j*len, len);
13
                if (counts.find(word) != counts.end()) {
14
                    seen[word]++;
15
                    if (seen[word] > counts[word])
16
                        break;
17
                } 
18
                else break;
19
                j++;
20
            }
21
            if (j == num) indexes.push_back(i);
22
        }
23
        return indexes;
24
    }
25
};







阅读全文
0 0
原创粉丝点击