150. Evaluate Reverse Polish Notation

  • μŠ€νƒμ„ μ΄μš©ν•˜μ—¬ μˆ«μžλ“€μ„ μ €μž₯ν•˜κ³  μ—°μ‚°μžκ°€ λ‚˜μ˜¬ λ•Œ λ§ˆλ‹€ μŠ€νƒμ—μ„œ 숫자λ₯Ό 2개 κΊΌλ‚΄μ„œ νŠΉμ • μ—°μ‚°μžλ₯Ό μ μš©ν•˜λ©΄ λœλ‹€.
    • μŠ€νƒμ˜ κΈΈμ΄λŠ” token의 수λ₯Ό λ„˜μ„ 수 μ—†μœΌλ―€λ‘œ λ™μΌν•œ 길이의 integer array둜 μ„ μ–Έν•˜μ—¬ stack을 λŒ€μ‹ ν•  수 μžˆλ‹€.
    • int[]λ₯Ό μ‚¬μš©ν•˜λ©΄ Stack<Integer> 으둜 κ΅¬ν˜„ν–ˆμ„ λ•Œ 보닀 1.5 ~ 2λ°° κ°€λŸ‰ λΉ λ₯΄λ‹€.
class Solution { public int evalRPN(String[] tokens) { int[] stack = new int[tokens.length]; int top = -1; for (String token : tokens) { char c = token.charAt(0); int value = 0, lhs, rhs; if (token.length() == 1 && (c < '0' || c > '9')) { rhs = stack[top--]; lhs = stack[top--]; switch (c) { case '+': value = lhs + rhs; break; case '-': value = lhs - rhs; break; case '*': value = lhs * rhs; break; case '/': value = lhs / rhs; break; } stack[++top] = value; } else if (c == '-') { stack[++top] = -Integer.parseInt(token.substring(1)); } else { stack[++top] = Integer.parseInt(token); } } return stack[top]; } }