Skip to content

Commit

Permalink
Refactored 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 9294d3e commit 74fefba
Showing 1 changed file with 11 additions and 21 deletions.
32 changes: 11 additions & 21 deletions src/leetcode/reverse_polish_notation.rs
Original file line number Diff line number Diff line change
@@ -1,28 +1,18 @@
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)
if let Ok(n) = token.parse() {
stack.push(n);
} else {
let rhs = stack.pop().unwrap();
let lhs = stack.pop().unwrap();
match token.as_str() {
"+" => stack.push(lhs + rhs),
"-" => stack.push(lhs - rhs),
"*" => stack.push(lhs * rhs),
"/" => stack.push(lhs / rhs),
_ => {}
}
"-" => {
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]
Expand Down

0 comments on commit 74fefba

Please sign in to comment.