-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubstring-with-concatenation-of-all-words.ts
64 lines (49 loc) · 1.2 KB
/
substring-with-concatenation-of-all-words.ts
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
function findSubstring(s: string, words: string[]): number[] {
const res: number[] = [];
const map: Record<string, number> = {};
for (let i = 0; i < words.length; i++) {
map[words[i]] = ~~map[words[i]] + 1;
}
let wordsLen = words.length;
let len = words[0].length;
for (let i = 0; i < len; i++) {
search(s, map, res, i, len, wordsLen);
}
return res;
}
function search(
s: string,
map: Record<string, number>,
res: number[],
i: number,
len: number,
wordsLen: number
) {
let seen: Record<string, number> = {};
let count = 0;
let start = i;
for (let j = i; i <= s.length - len; i += len) {
const word = s.substring(i, i + len);
if (map[word]) {
seen[word] = ~~seen[word] + 1;
count++;
while (seen[word] > map[word]) {
let left = s.substring(start, start + len);
seen[left] = ~~seen[left] - 1;
count--;
start = start + len;
}
if (count === wordsLen) {
res.push(start);
let left = s.substring(start, start + len);
seen[left] = ~~seen[left] - 1;
count--;
start = start + len;
}
} else {
seen = {};
start = i + len;
count = 0;
}
}
}