-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathevaluate_reverse_polish_notation.go
More file actions
47 lines (40 loc) · 1.04 KB
/
evaluate_reverse_polish_notation.go
File metadata and controls
47 lines (40 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
150. Evaluate Reverse Polish Notation
https://leetcode.com/problems/evaluate-reverse-polish-notation/
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid.
That means the expression would always evaluate to a result and there won't be any divide by zero operation.
*/
// time: 2019-01-07
package evaluatereversepolishnotation
import "strconv"
// stack
// time complexity: O(n)
// space complexity: O(n)
func evalRPN(tokens []string) int {
stack := make([]int, len(tokens))
top := -1
for i := 0; i < len(tokens); i++ {
switch ch := tokens[i]; ch {
case "+":
stack[top-1] += stack[top]
top--
case "-":
stack[top-1] -= stack[top]
top--
case "*":
stack[top-1] *= stack[top]
top--
case "/":
stack[top-1] /= stack[top]
top--
default:
top++
stack[top], _ = strconv.Atoi(ch)
}
}
return stack[0]
}