-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday-4.js
27 lines (22 loc) · 975 Bytes
/
day-4.js
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
// In 🎅 Santa's workshop, some Christmas messages have been written in a peculiar way: the words within the brackets must be read backwards.
// Santa needs these messages to be correctly formatted.
// Your task is to write a function that takes a string and reverses the characters within each pair of parentheses, removing the parentheses as well.
// However, bear in mind that there may be nested parentheses, so you should reverse the characters in the correct order.
function decode(message) {
let stack = [];
let result = '';
for (let char of message) {
if (char === '(') {
// Push the current result to the stack and reset it
stack.push(result);
result = '';
} else if (char === ')') {
// Pop the previous result from the stack and reverse it
result = stack.pop() + result.split('').reverse().join('');
} else {
// Append characters to the current result
result += char;
}
}
return result;
}