150. Evaluate Reverse Polish Notation
Tags:
Medium
Skills:
Stack
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Để giải bài tập này, bạn nên sử dụng stack để lưu trữ toán hạng. Khi gặp toán tử, bạn lấy ra hai phần tử gần nhất trên stack, thực hiện phép tính rồi đẩy kết quả trở lại stack. Lặp lại cho đến hết mảng tokens, kết quả cuối cùng sẽ là phần tử duy nhất còn lại trên stack
Approach
Math.trunc hoặc ép kiểu về số nguyên sau khi chiaTime and space complexity
Solution
1function evalRPN(tokens: string[]): number {
2 const stack: number[] = [];
3 for (const token of tokens) {
4 if (token === '-' || token === '+' || token === '*' || token === '/') {
5 let res = 0
6 const b = stack.pop();
7 const a = stack.pop();
8 switch (token) {
9 case "+": {
10 res = a + b;
11 break;
12 }
13 case "-": {
14 res = a - b;
15 break;
16 }
17 case '*': {
18 res = a * b
19 break;
20 }
21 case "/": {
22 res = Math.trunc(a / b)
23 break;
24 }
25 }
26
27 stack.push(res)
28 } else {
29 stack.push(Number(token))
30 }
31 }
32
33 return stack[0]
34};