|
| 1 | +// https://leetcode.com/problems/evaluate-reverse-polish-notation |
| 2 | +// |
| 3 | +// Evaluate the value of an arithmetic expression in [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). |
| 4 | +// |
| 5 | +// Valid operators are `+`, `-`, `*`, and `/`. Each operand may be an integer or another expression. |
| 6 | +// |
| 7 | +// **Note** that division between two integers should truncate toward zero. |
| 8 | +// |
| 9 | +// 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. |
| 10 | +// |
| 11 | +// **Example 1:** |
| 12 | +// |
| 13 | +// ``` |
| 14 | +// **Input:** tokens = ["2","1","+","3","*"] |
| 15 | +// **Output:** 9 |
| 16 | +// **Explanation:** ((2 + 1) * 3) = 9 |
| 17 | +// ``` |
| 18 | +// |
| 19 | +// **Example 2:** |
| 20 | +// |
| 21 | +// ``` |
| 22 | +// **Input:** tokens = ["4","13","5","/","+"] |
| 23 | +// **Output:** 6 |
| 24 | +// **Explanation:** (4 + (13 / 5)) = 6 |
| 25 | +// ``` |
| 26 | +// |
| 27 | +// **Example 3:** |
| 28 | +// |
| 29 | +// ``` |
| 30 | +// **Input:** tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"] |
| 31 | +// **Output:** 22 |
| 32 | +// **Explanation:** ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 |
| 33 | +// = ((10 * (6 / (12 * -11))) + 17) + 5 |
| 34 | +// = ((10 * (6 / -132)) + 17) + 5 |
| 35 | +// = ((10 * 0) + 17) + 5 |
| 36 | +// = (0 + 17) + 5 |
| 37 | +// = 17 + 5 |
| 38 | +// = 22 |
| 39 | +// ``` |
| 40 | +// |
| 41 | +// **Constraints:** |
| 42 | +// |
| 43 | +// * `1 <= tokens.length <= 10<sup>4</sup>` |
| 44 | +// * `tokens[i]` is either an operator: `"+"`, `"-"`, `"*"`, or `"/"`, or an integer in the range `[-200, 200]`. |
| 45 | + |
| 46 | +pub fn eval_rpn(tokens: Vec<String>) -> i32 { |
| 47 | + let mut stack = Vec::new(); |
| 48 | + for token in tokens { |
| 49 | + if token == "+" { |
| 50 | + let a = stack.pop().unwrap(); |
| 51 | + let b = stack.pop().unwrap(); |
| 52 | + stack.push(a + b); |
| 53 | + } else if token == "-" { |
| 54 | + let a = stack.pop().unwrap(); |
| 55 | + let b = stack.pop().unwrap(); |
| 56 | + stack.push(b - a); |
| 57 | + } else if token == "*" { |
| 58 | + let a = stack.pop().unwrap(); |
| 59 | + let b = stack.pop().unwrap(); |
| 60 | + stack.push(a * b); |
| 61 | + } else if token == "/" { |
| 62 | + let a = stack.pop().unwrap(); |
| 63 | + let b = stack.pop().unwrap(); |
| 64 | + stack.push(b / a); |
| 65 | + } else { |
| 66 | + stack.push(token.parse::<i32>().unwrap()); |
| 67 | + } |
| 68 | + } |
| 69 | + return stack.pop().unwrap(); |
| 70 | +} |
| 71 | + |
| 72 | +#[test] |
| 73 | +pub fn t1() { |
| 74 | + assert_eq!( |
| 75 | + eval_rpn( |
| 76 | + vec!["2", "1", "+", "3", "*"] |
| 77 | + .iter() |
| 78 | + .map(|x| x.to_string()) |
| 79 | + .collect() |
| 80 | + ), |
| 81 | + 9 |
| 82 | + ); |
| 83 | +} |
0 commit comments