-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0791-custom-sort-string.js
More file actions
47 lines (43 loc) · 1.43 KB
/
0791-custom-sort-string.js
File metadata and controls
47 lines (43 loc) · 1.43 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
/**
* Custom Sort String
* Time Complexity: O(S_LEN + T_LEN)
* Space Complexity: O(T_LEN)
*/
var customSortString = function (sOrderString, tSourceString) {
const characterFrequencies = new Array(26).fill(0);
const alphaCodeOffset = "a".charCodeAt(0);
let tIndex = 0;
const tSourceLength = tSourceString.length;
while (tIndex < tSourceLength) {
const currentTCharCode = tSourceString.charCodeAt(tIndex);
const frequencyIndex = currentTCharCode - alphaCodeOffset;
characterFrequencies[frequencyIndex]++;
tIndex++;
}
const resultArray = [];
let sIndex = 0;
const sOrderLength = sOrderString.length;
while (sIndex < sOrderLength) {
const sCurrentCharCode = sOrderString.charCodeAt(sIndex);
const sFrequencyIndex = sCurrentCharCode - alphaCodeOffset;
let repetitionCount = characterFrequencies[sFrequencyIndex];
while (repetitionCount > 0) {
resultArray.push(String.fromCharCode(sCurrentCharCode));
repetitionCount--;
}
characterFrequencies[sFrequencyIndex] = 0;
sIndex++;
}
let alphaIndex = 0;
const alphabetRange = 26;
while (alphaIndex < alphabetRange) {
const remainingCharAscii = alphaIndex + alphaCodeOffset;
let remainingCharCount = characterFrequencies[alphaIndex];
while (remainingCharCount > 0) {
resultArray.push(String.fromCharCode(remainingCharAscii));
remainingCharCount--;
}
alphaIndex++;
}
return resultArray.join("");
};