diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /eval_reverse_polish_notation.rs | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'eval_reverse_polish_notation.rs')
-rw-r--r-- | eval_reverse_polish_notation.rs | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/eval_reverse_polish_notation.rs b/eval_reverse_polish_notation.rs new file mode 100644 index 0000000..11a36e3 --- /dev/null +++ b/eval_reverse_polish_notation.rs @@ -0,0 +1,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)); +} |