var scoreOfParentheses = function (s) {
let stack = [];
let count;
for (let i = 0; i < s.length; i++) {
if (s[i] === '(') {
stack.push('(');
} else {
if (stack[stack.length - 1] === '(') {
stack.pop();
stack.push(1);
} else if (typeof stack[stack.length - 1] === 'number' && stack[stack.length - 2] === '(') {
count = stack.pop();
stack.pop();
stack.push(2 * count);
}
// ๋ด๊ฐ ์ง์ ๊ตฌํ ๋ชปํ ๋ถ๋ถ
while (
stack.length &&
typeof stack[stack.length - 1] === 'number' &&
typeof stack[stack.length - 2] === 'number'
) {
stack.push(stack.pop() + stack.pop());
}
}
}
return stack.pop();
};
// Optimal Solution(Stack) - ๋ค๋ฅธ ์ฌ๋์ ํ์ด
const scoreOfParentheses = function (str) {
// beginning score - ์ง์ ํด์ฃผ์ง ์์ผ๋ฉด stack.pop์ ํ ๋ ์ค๋ฅ๊ฐ ๋ ๊ฒ์ด๋ค.
let stack = [0];
for (let s of str) {
if (s === '(') {
stack.push(0);
} else {
let top = stack.pop();
let beforeTop = stack.pop();
stack.push(beforeTop + Math.max(2 * top, 1));
// Result of first else
// [0, 1]
// Result of second else
// [0, 1, 1]
// Result of third else
// [0, 3]
// Result of final else
// [6]
}
}
return stack.pop();
};
Stack, Divide and Conquer, recursive ๋ฑ ์ฌ๋ฌ ๋ฐฉ๋ฒ์ด ์์๋ค. ๊ทธ ์ค ๋๋ Stack์ ์ ํํด์ ๋ฌธ์ ๋ฅผ ํ์๋๋ฐ, ๋ง์ง๋ง ์กฐ๊ฑด์ธ
ํด๋น ์กฐ๊ฑด์ ๋ํ ๋ต์ ๊ฒฐ๊ตญ ์ค์ค๋ก ํด๊ฒฐํ์ง ๋ชปํ๊ณ Discussion์ ์ฐธ๊ณ ํ๋ค. ๋งจ ์์ "stack.length
๊ฐ ์์๋"๋ผ๋ ์กฐ๊ฑด์ ๋น ๋จ๋ฆฐ ๊ฒ์ด ๋ฌธ์ ์๋ค. ํด๋น while
๋ฌธ์ ์ฝ๋๋ฅผ ๋ณด๋ฉด stack.pop()
์ 2๋ฒ ํ๋๋ฐ, ๋น์ฐํ๊ฒ๋ stack ๋ฐฐ์ด ์์ ๊ฐ์ด ์๋ค๋ฉด ์๋ ์ฝ๋๋ฅผ ์คํ์ํค์ง ๋ชปํ๋ ๊ฒ์ด ์์ธ์ด์๋ค. ์ด๋ ค์ด ๋ฌธ์ ์๋ค.
https://leetcode.com/problems/score-of-parentheses/
https://github.com/tTab1204/LeetCode/tree/main/%EC%A3%BC%EC%98%81