您的位置:首页 > 其它

Leetcode(10) - Substring with Concatenation of All Words

2017-05-07 23:18 337 查看
https://leetcode.com/problems/substring-with-concatenation-of-all-words/#/description

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:

这道题的解法是,从前往后遍历string s,每次遍历当前位置的words.size() * words[0].length()的substring,用两个Map来记录words是否匹配,当匹配则将i放入返回值中。

这里有个小错误,我一开始以为words不会重复,所以用了set,但是,好吧,好坑。

class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> indexs;
map<string, int> words_set;

for(string word : words) {
words_set[word]++;
}

int word_len = words[0].length();
for(int i = 0; i < s.length() - words.size() * word_len + 1; i++) {
map<string, int> exist;
int stop_index = i + words.size() * word_len;
for(int start = i; start < stop_index;) {
string s2 = s.substr(start, word_len);
if(words_set.find(s2) != words_set.end()) {
exist[s2]++;
if(exist[s2] <= words_set[s2]) {
start += word_len;
if(start == stop_index) {
indexs.push_back(i);
} else {
continue;
}
}
}

break;
}
}

return indexs;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: