Skip to content

Commit

Permalink
Added reverse polish notation solution.
Browse files Browse the repository at this point in the history
  • Loading branch information
jusexton committed Dec 29, 2024
1 parent f946725 commit 9294d3e
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions src/leetcode/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
44 changes: 44 additions & 0 deletions src/leetcode/reverse_polish_notation.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
pub fn eval_rpn(tokens: Vec<String>) -> 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::<i32>().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", "/", "+"]))
}
}

0 comments on commit 9294d3e

Please sign in to comment.