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.
Example 1:
Input:
s = “barfoothefoobarman”,
words = [“foo”,“bar”]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are “barfoor” and “foobar” respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:
Input:
s = “wordgoodgoodgoodbestword”,
words = [“word”,“good”,“best”,“word”]
Output: []
Approach
题目大意:从一组字符串中找到连续一串与words所有字符串组合相同
解题思路:使用滑动窗口的思想,设words中单词长为len,我们就可以从字符串s的0~len出发(为什么只用从0~len出发呢,因为words的每个单词长度是确定的,这样其实从字符串0~len出发每次递增len长度,你会发现全都会访问到。),每次递增单词长度就为len,窗口大小维护为words的大小,这样当不连续的时候,就消减窗口,直到连续为止,这样当窗口大小又等于words的大小的时候就可以把头放入vector中。
Code
class Solution {
public:
vector<int> findSubstring(string s, vector<string> &words) {
if (s.empty() || words.empty())
return vector<int>();
vector<int> ans;
int m = words[0].size(), n = s.size(), sum = words.size(), nn = n - m;
unordered_map<string, int> count;
for (const string &w:words)count[w]++;
for (int i = 0; i < m; i++) {
unordered_map<string, int> mp;
int left = i, cnt = 0;
for (int j = i; j <= nn; j+=m) {
string tmp = s.substr(j, m);
if (!count.count(tmp)) {
cnt = 0;
left = j+m;
mp.clear();
continue;
}
mp[tmp]++;
if (mp[tmp] <= count[tmp])cnt++;
else {
while (mp[tmp] > count[tmp]) {
string stmp = s.substr(left, m);
mp[stmp]--;
left += m;
cnt--;
}
cnt++;
}
if (cnt == sum) {
ans.push_back(left);
}
}
}
return ans;
}
};