๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 394 - Decode String (Medium)

by HandHand 2021. 3. 3.

๋ฌธ์ œ

LeetCode - 394๋ฒˆ

ํ’€์ด ๊ณผ์ •

๋ฌธ์ž์—ด์˜ ๊ทœ์น™์— ๋”ฐ๋ผ ๋””์ฝ”๋”ฉํ•˜์—ฌ ์›๋ณธ ๋ฌธ์ž์—ด์„ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.
[ ๊ด„ํ˜ธ ์•ž์—๋Š” ๋ฐ˜๋ณตํ•  ์ˆซ์ž๊ฐ€ ์ฃผ์–ด์ง€๊ธฐ ๋•Œ๋ฌธ์— ์Šคํƒ ์„ ํ™œ์šฉํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜์˜€์Šต๋‹ˆ๋‹ค.

๋จผ์ € ๋ฌธ์ž์—ด์˜ ๊ฐ ๋ฌธ์ž๋ฅผ ์ˆœํšŒํ•˜๋ฉฐ [ ์™€ ] ๊ทธ๋ฆฌ๊ณ  ์ˆซ์ž ๋ฅผ ์ œ์™ธํ•œ ๋ฌธ์ž๋“ค์€ ๊ทธ๋ƒฅ push ํ•ด์ค๋‹ˆ๋‹ค.
๋งŒ์•ฝ ์ˆซ์ž๋ฅผ ๋งŒ๋‚  ๊ฒฝ์šฐ์—๋Š” ํ˜„์žฌ ์Šคํƒ์˜ top ์ด ์ˆซ์ž์ธ์ง€ ํŒ๋‹จํ•˜๊ณ  ์ˆซ์ž๋ผ๋ฉด ํ•ด๋‹น ์ˆซ์ž์— ์ด์–ด๋ถ™์ž…๋‹ˆ๋‹ค.
(๋‘ ์ž๋ฆฌ์ˆ˜ ์ด์ƒ์ด ์žˆ์„ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์—)

์ดํ›„ ] ๋ฅผ ๋งŒ๋‚˜๋ฉด [ ๊ฐ€ ๋ฐœ๊ฒฌ๋  ๋•Œ ๊นŒ์ง€ ๋ฌธ์ž๋“ค์„ pop ํ•˜๊ณ  [ ์•ž์˜ ์ˆซ์ž๋งŒํผ repeat ํ•ด์ค๋‹ˆ๋‹ค.
์ตœ์ข…์ ์œผ๋กœ ์Šคํƒ ์— ๋‚จ์•„์žˆ๋Š” ๋ฌธ์ž๋“ค์„ ๋ชจ๋‘ ํ•ฉ์ณ์ฃผ๋ฉด ์šฐ๋ฆฌ๊ฐ€ ์ฐพ๋Š” ์›๋ณธ ๋ฌธ์ž์—ด์ด ๋ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {string} s
 * @return {string}
 */
var decodeString = function (s) {
  const stack = [];

  for (let c of s) {
    if (c === "]") {
      let temp = "";
      while (stack[stack.length - 1] !== "[") {
        temp = stack.pop() + temp;
      }
      stack.pop();
      temp = temp.repeat(parseInt(stack.pop()));
      stack.push(temp);
    } else if (!isNaN(c)) {
      if (!isNaN(stack[stack.length - 1])) {
        stack[stack.length - 1] += c;
      } else {
        stack.push(c);
      }
    } else {
      stack.push(c);
    }
  }

  return stack.join("");
};
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 279 - Perfect Squares (Medium)  (0) 2021.03.03
LeetCode 94 - Binary Tree Inorder Traversal (Medium)  (0) 2021.03.03
LeetCode 78 - Subsets (Medium)  (0) 2021.03.03
LeetCode 739 - Daily Temperatures (Medium)  (0) 2021.03.03
LeetCode 114 - Flatten Binary Tree to Linked List (Medium)  (0) 2021.03.03

๐Ÿ’ฌ ๋Œ“๊ธ€