.Zzumbong

[leetCode/JS] 150. Evaluate Reverse Polish Notation ๋ณธ๋ฌธ

coding test/leetCode

[leetCode/JS] 150. Evaluate Reverse Polish Notation

์ญ˜๋ด‰ 2022. 12. 17. 21:44

๋‚œ์ด๋„ [ ๐Ÿค” ] Medium 

 

๋ฌธ์ œ ์„ค๋ช… 

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, and /. Each operand may be an integer or another expression.

Note that division between two integers should truncate toward zero.

It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.

 

์—ญํด๋ž€๋“œํ‘œ๊ธฐ๋ฒ•? ์œผ๋กœ ๋งŒ๋“ค์–ด์ง„ ๋ฐฐ์—ด์„ ๊ณ„์‚ฐํ•˜๋Š” ๊ฒƒ์ด๋‹ค. ์—ญํด๋ž€๋“œํ‘œ๊ธฐ๋ฒ•์€ ์ƒ๊ฐ๋ณด๋‹ค ์‰ฝ๋‹ค. 
์—ฐ์‚ฐ์ž๊ฐ€ ๋‚˜์˜ค๋Š” i ๊ธฐ์ค€์œผ๋กœ [i-2] [i] [i-1] ์œผ๋กœ ์—ฐ์‚ฐ ํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

 

 

์ž…์ถœ๋ ฅ ์˜ˆ

Example 1:

Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9

 

Example 2:

Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

 

Example 3:

Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

 

 

 

Constraints

  • 1 <= tokens.length <= 104
  • tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].

 

 

 


๋‚ด ์†”๋ฃจ์…˜

  • ์—ฐ์‚ฐ์ž object์— ๊ฐ ์—ฐ์‚ฐ์ž ๋ณ„ ํ•จ์ˆ˜๋ฅผ ์ €์žฅํ•ด๋‘๊ณ  ์—ฐ์‚ฐ์ž๋ฅผ ๋งŒ๋‚˜๊ฒŒ๋˜๋ฉด tokens[i-2], tokens[i-1] ์„ ์—ฐ์‚ฐํ•œ๋‹ค.
  • ์—ฐ์‚ฐ๋œ ๊ฒฐ๊ณผ๊ฐ’์„ ๋‹ค์‹œ tokens์— ์ง‘์–ด ๋„ฃ์ง€๋งŒ splice()๋ฅผ ํ†ตํ•ด [i-2], [i-1], [i] ๋ฅผ ์ง€์šฐ๊ณ  ๋„ฃ๋Š”๋‹ค.
  • i ๋Š” -2 ๋งŒํผ ๋’ค๋กœ ๋Œ๋ ค์ฃผ๋ฉด ๋œ๋‹ค.
  • for loop๊ฐ€ ๋๋‚˜๋ฉด ๋งˆ์ง€๋ง‰์— ์ˆซ์ž 1๊ฐœ๋งŒ ๋‚จ์•„์žˆ๊ฒŒ ๋˜๋‹ˆ tokens[0] ์„ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋๋‚œ๋‹ค. 
var evalRPN = function(tokens) {
  const operations = {
    '+': (a, b) => a + b,
    '-': (a, b) => a - b,
    '*': (a, b) => a * b,
    '/': (a, b) => a / b | 0, // or Math.trunc()
  }
  for(let i = 0; i < tokens.length; i++) {
    if(tokens[i] in operations) { // ๋ฐฐ์—ด ์•ˆ์— ์žˆ๋Š”์ง€ ์—†๋Š”์ง€ ์•Œ์•„๋‚ด๋Š” ์‰ฌ์šด ๋ฐฉ๋ฒ•
      tokens.splice(i-2, 3, operations[tokens[i]](parseInt(tokens[i-2]), parseInt(tokens[i-1])))
      i -= 2;
    }
  }
  return tokens[0];
};

 

๊ฐ์ƒํ‰

  • ์—ญํด๋ž€๋“œํ‘œ๊ธฐ๋ฒ•์€ ๊ด„ํ˜ธ๊ฐ€ ํ•„์š” ์—†๋‹ค๋Š” ์ ์—์„œ ๊ต‰์žฅํžˆ ์œ ์šฉํ•œ ์ˆ˜์‹ ํ‘œํ˜„๋ฒ•์ด ์•„๋‹๊นŒ ์‹ถ๋‹ค.
  • ๋„ˆ๋ฌด ์žฌ๋ฏธ์žˆ๋Š” ํ‘œ๊ธฐ๋ฒ•์„ ๋ฐฐ์›Œ์„œ ๋งŒ์กฑ์Šค๋Ÿฌ์šด ๋ฌธ์ œ์˜€๋‹ค.

'coding test > leetCode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[leetCode/JS] 841. Keys and Rooms  (0) 2022.12.20
[leetCode/JS] 739. Daily Temperatures  (0) 2022.12.18
[leetCode/JS] 232. Implement Queue using Stacks  (0) 2022.12.16
[leetCode/JS] 1143. Longest Common Subsequence  (0) 2022.12.15
[leetCode/JS] 152. Maximum Product Subarray  (0) 2022.12.14
0 Comments
๋Œ“๊ธ€์“ฐ๊ธฐ ํผ