-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0567-permutation-in-string.js
More file actions
54 lines (46 loc) · 1.47 KB
/
0567-permutation-in-string.js
File metadata and controls
54 lines (46 loc) · 1.47 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
/**
* Permutation In String
* Time Complexity: O(N)
* Space Complexity: O(1)
*/
var checkInclusion = function (s1, s2) {
const getCharacterOffset = (charValue) =>
charValue.charCodeAt(0) - "a".charCodeAt(0);
const compareFrequencyMaps = (mapA, mapB) => {
for (let charIndex = 0; charIndex < 26; charIndex++) {
if (mapA[charIndex] !== mapB[charIndex]) {
return false;
}
}
return true;
};
const stringOneLength = s1.length;
const stringTwoLength = s2.length;
if (stringOneLength > stringTwoLength) {
return false;
}
const firstStringCounts = new Array(26).fill(0);
const currentWindowCounts = new Array(26).fill(0);
for (
let initialPopulateIndex = 0;
initialPopulateIndex < stringOneLength;
initialPopulateIndex++
) {
firstStringCounts[getCharacterOffset(s1[initialPopulateIndex])]++;
currentWindowCounts[getCharacterOffset(s2[initialPopulateIndex])]++;
}
for (
let windowMoveIndex = 0;
windowMoveIndex < stringTwoLength - stringOneLength;
windowMoveIndex++
) {
if (compareFrequencyMaps(firstStringCounts, currentWindowCounts)) {
return true;
}
const charLeavingWindow = s2[windowMoveIndex];
const charEnteringWindow = s2[windowMoveIndex + stringOneLength];
currentWindowCounts[getCharacterOffset(charLeavingWindow)]--;
currentWindowCounts[getCharacterOffset(charEnteringWindow)]++;
}
return compareFrequencyMaps(firstStringCounts, currentWindowCounts);
};