-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0438-find-all-anagrams-in-a-string.js
More file actions
62 lines (50 loc) · 1.84 KB
/
0438-find-all-anagrams-in-a-string.js
File metadata and controls
62 lines (50 loc) · 1.84 KB
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
/**
* Find All Anagrams In A String
* Time Complexity: O(s.length + p.length)
* Space Complexity: O(1)
*/
var findAnagrams = function (s, p) {
const patternCharacterCounts = new Array(26).fill(0);
const resultStartingIndices = [];
const sourceLength = s.length;
const patternLength = p.length;
if (sourceLength < patternLength) {
return resultStartingIndices;
}
for (let currentPCharIndex = 0; currentPCharIndex < patternLength; currentPCharIndex++) {
const charCodeP = p.charCodeAt(currentPCharIndex) - 97;
patternCharacterCounts[charCodeP]--;
}
let zeroBalanceCount = 0;
for (let charEntryIndex = 0; charEntryIndex < 26; charEntryIndex++) {
if (patternCharacterCounts[charEntryIndex] === 0) {
zeroBalanceCount++;
}
}
let windowLeftPointer = 0;
for (let windowRightPointer = 0; windowRightPointer < sourceLength; windowRightPointer++) {
const charCodeS = s.charCodeAt(windowRightPointer) - 97;
if (patternCharacterCounts[charCodeS] === 0) {
zeroBalanceCount--;
}
patternCharacterCounts[charCodeS]++;
if (patternCharacterCounts[charCodeS] === 0) {
zeroBalanceCount++;
}
if (windowRightPointer - windowLeftPointer + 1 === patternLength) {
if (zeroBalanceCount === 26) {
resultStartingIndices.push(windowLeftPointer);
}
const charCodeLeft = s.charCodeAt(windowLeftPointer) - 97;
if (patternCharacterCounts[charCodeLeft] === 0) {
zeroBalanceCount--;
}
patternCharacterCounts[charCodeLeft]--;
if (patternCharacterCounts[charCodeLeft] === 0) {
zeroBalanceCount++;
}
windowLeftPointer++;
}
}
return resultStartingIndices;
};