856. Score of Parentheses

๋Š˜๋ณดยท2021๋…„ 7์›” 10์ผ
0

LeetCode

๋ชฉ๋ก ๋ณด๊ธฐ
5/69

๐Ÿ’กํ’€์ด

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/

LeetCode GitHub

https://github.com/tTab1204/LeetCode/tree/main/%EC%A3%BC%EC%98%81

0๊ฐœ์˜ ๋Œ“๊ธ€