From 9294d3e441bb05246f1d4e378c13d42de17d0320 Mon Sep 17 00:00:00 2001 From: jusexton Date: Sat, 28 Dec 2024 18:21:05 -0600 Subject: [PATCH] Added reverse polish notation solution. --- README.md | 1 + src/leetcode/mod.rs | 1 + src/leetcode/reverse_polish_notation.rs | 44 +++++++++++++++++++++++++ 3 files changed, 46 insertions(+) create mode 100644 src/leetcode/reverse_polish_notation.rs diff --git a/README.md b/README.md index 4fc0270..1362c93 100644 --- a/README.md +++ b/README.md @@ -259,6 +259,7 @@ programming challenges completed in other languages. - [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes) - [Group Anagrams](https://leetcode.com/problems/group-anagrams) - [Min Stack](https://leetcode.com/problems/min-stack) +- [Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation) #### Hard diff --git a/src/leetcode/mod.rs b/src/leetcode/mod.rs index 9be0f5f..82265b1 100644 --- a/src/leetcode/mod.rs +++ b/src/leetcode/mod.rs @@ -121,6 +121,7 @@ mod repeat_limit; mod repeated_dna; mod replace_digits; mod return_to_origin; +mod reverse_polish_notation; mod roman_to_int; mod rotate_array; mod rotate_box; diff --git a/src/leetcode/reverse_polish_notation.rs b/src/leetcode/reverse_polish_notation.rs new file mode 100644 index 0000000..99784b4 --- /dev/null +++ b/src/leetcode/reverse_polish_notation.rs @@ -0,0 +1,44 @@ +pub fn eval_rpn(tokens: Vec) -> i32 { + let mut stack = vec![]; + for token in tokens { + match token.as_str() { + "+" => { + let b = stack.pop().unwrap(); + let a = stack.pop().unwrap(); + stack.push(a + b) + } + "-" => { + let b = stack.pop().unwrap(); + let a = stack.pop().unwrap(); + stack.push(a - b) + } + "*" => { + let b = stack.pop().unwrap(); + let a = stack.pop().unwrap(); + stack.push(a * b) + } + "/" => { + let b = stack.pop().unwrap(); + let a = stack.pop().unwrap(); + stack.push(a / b) + } + _ => stack.push(token.parse::().unwrap()), + } + } + stack[0] +} + +#[cfg(test)] +mod tests { + use crate::string_vec; + + use super::*; + + #[test] + fn evaluates_reverse_ploish_notation_expression() { + assert_eq!(15, eval_rpn(string_vec!["5", "10", "+"])); + assert_eq!(10, eval_rpn(string_vec!["5", "10", "+", "5", "-"])); + assert_eq!(9, eval_rpn(string_vec!["2", "1", "+", "3", "*"])); + assert_eq!(6, eval_rpn(string_vec!["4", "13", "5", "/", "+"])) + } +}