[LeetCode] Substring with Concatenation of All Words

30. Substring with Concatenation of All Words

You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters.

You can return the answer in any order.

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
class Solution {
unordered_map<string, int> mp;
int len, totlen;
bool verify(string& s, int i) {
unordered_map<string,int> tmp;
for(int st = i; st < i + totlen; st+=len) {
string w = s.substr(st,len);
if(!mp.count(w) or mp[w] < ++tmp[w]) return false;
}
return true;
}
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> res;
len = words[0].length(), totlen = words.size() * len;


for(auto w : words) mp[w]++;
for(int i = 0; i <= (int)s.length() - totlen; i++) {
if(verify(s,i))
res.push_back(i);
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/22/PS/LeetCode/substring-with-concatenation-of-all-words/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.