aboutsummaryrefslogtreecommitdiff
path: root/eval_reverse_polish_notation.rs
blob: 11a36e3793c6973236a01b26bc54be8ea8fdc9ff (plain)
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
struct Solution;

impl Solution {
    pub fn eval_rpn(tokens: Vec<String>) -> i32 {
        tokens.iter().fold(Vec::new(), |mut stack, x| {
            if let Ok(x) = x.parse() {
                stack.push(x);
            } else if let (Some(rhs), Some(lhs)) = (stack.pop(), stack.pop()) {
                stack.push(match x.as_str() {
                    "+" => lhs + rhs,
                    "-" => lhs - rhs,
                    "*" => lhs * rhs,
                    "/" => lhs / rhs,
                    _   => unreachable!()
                })
            }
            stack
        }) [0]
    }
}

fn main() {
    let tokens1 = ["2","1","+","3","*"];
    let tokens2 = ["4","13","5","/","+"];
    let tokens3 = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"];
    println!("{}", Solution::eval_rpn(tokens1));
    println!("{}", Solution::eval_rpn(tokens2));
    println!("{}", Solution::eval_rpn(tokens3));
}