-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluate_reverse_polish_notation.rs
99 lines (91 loc) · 2.43 KB
/
evaluate_reverse_polish_notation.rs
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#![allow(dead_code)]
pub fn eval_rpn(tokens: Vec<String>) -> i32 {
let mut stack = Vec::new();
for token in tokens {
match token.as_str() {
"+" => {
let a = stack.pop().unwrap();
let b = stack.pop().unwrap();
stack.push(a + b);
}
"-" => {
let a = stack.pop().unwrap();
let b = stack.pop().unwrap();
stack.push(b - a);
}
"*" => {
let a = stack.pop().unwrap();
let b = stack.pop().unwrap();
stack.push(a * b);
}
"/" => {
let a = stack.pop().unwrap();
let b = stack.pop().unwrap();
stack.push(b / a);
}
_ => {
stack.push(token.parse::<i32>().unwrap());
}
}
}
stack.pop().unwrap()
}
/*
Algorithm - Stack
- Create a stack
- Iterate through the tokens
- If the current token is an operator
- Pop the top two elements from the stack
- Perform the operation on the two elements
- Push the result back onto the stack
- Else
- Push the current token onto the stack
- Return the top element of the stack
Time: O(n)
Space: O(n)
*/
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_150() {
assert_eq!(
eval_rpn(vec![
"2".to_string(),
"1".to_string(),
"+".to_string(),
"3".to_string(),
"*".to_string()
]),
9
);
assert_eq!(
eval_rpn(vec![
"4".to_string(),
"13".to_string(),
"5".to_string(),
"/".to_string(),
"+".to_string()
]),
6
);
assert_eq!(
eval_rpn(vec![
"10".to_string(),
"6".to_string(),
"9".to_string(),
"3".to_string(),
"+".to_string(),
"-11".to_string(),
"*".to_string(),
"/".to_string(),
"*".to_string(),
"17".to_string(),
"+".to_string(),
"5".to_string(),
"+".to_string()
]),
22
);
}
}