-
Notifications
You must be signed in to change notification settings - Fork 2
/
decodeString.ts
36 lines (32 loc) · 1.32 KB
/
decodeString.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
type DecodeString = (s: string) => string;
/**
* Accepted
*/
export const decodeString: DecodeString = (s) => {
const countStack: number[] = []; // Stack to store repeat counts
const stringStack: string[] = []; // Stack to store intermediate strings
let currentNum = 0; // Current number being processed
let currentString = ''; // Current string being processed
for (const char of s) {
if (!Number.isNaN(Number(char))) {
// If the character is a digit, update currentNum
currentNum = currentNum * 10 + Number(char);
} else if (char === '[') {
// If the character is '[', push currentNum and currentString to stacks
countStack.push(currentNum);
stringStack.push(currentString);
currentNum = 0; // Reset currentNum
currentString = ''; // Reset currentString
} else if (char === ']') {
// If the character is ']', pop from stacks and update currentString
const repeatTimes = countStack.pop(); // Get the last count
const lastString = stringStack.pop(); // Get the last string
currentString = lastString + currentString.repeat(repeatTimes || 1); // Repeat currentString and append
} else {
// If the character is a letter, append it to currentString
currentString += char;
}
}
// Return the fully decoded string
return currentString;
};