diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 6e3bfed..86d27c2 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -135,4 +135,5 @@ mod p56_merge_intervals; mod p57_insert_interval; mod p452_minimum_number_of_arrows_to_burst_balloons; mod p71_simplify_path; -mod p155_min_stack; \ No newline at end of file +mod p155_min_stack; +mod p150_evaluate_reverse_polish_notation; \ No newline at end of file diff --git a/src/problem/p150_evaluate_reverse_polish_notation.rs b/src/problem/p150_evaluate_reverse_polish_notation.rs new file mode 100644 index 0000000..afedb06 --- /dev/null +++ b/src/problem/p150_evaluate_reverse_polish_notation.rs @@ -0,0 +1,43 @@ +/** + * [150] Evaluate Reverse Polish Notation + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn eval_rpn(tokens: Vec) -> i32 { + let mut stack = vec![]; + + for token in tokens { + if let Ok(num) = token.parse::() { + stack.push(num); + } else { + let second = stack.pop().unwrap(); + let first = stack.pop().unwrap(); + + match token.as_str() { + "+" => stack.push(first + second), + "-" => stack.push(first - second), + "*" => stack.push(first * second), + "/" => stack.push(first / second), + _ => {}, + } + } + } + + stack[0] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_150() { + assert_eq!(9, Solution::eval_rpn(vec_string!["2","1","+","3","*"])); + } +}