Browse Source

feat: evaluate_reverse_polish_notation

Zhang Li 11 months ago
parent
commit
ae55c70fc0

+ 52 - 0
src/solutions/stack/evaluate_reverse_polish_notation.rs

@@ -0,0 +1,52 @@
+
+struct Solution;
+impl Solution {
+    pub fn eval_rpn(tokens: Vec<String>) -> i32 {
+        let mut stack = vec![];
+        for i in 0..tokens.len() {
+            let v = &tokens[i][..];
+            match v {
+                "+" => {
+                    let num1 = stack.pop().unwrap();
+                    let num2 = stack.pop().unwrap();
+                    stack.push(num1 + num2);
+                },
+                "-" => {
+                    let num1 = stack.pop().unwrap();
+                    let num2 = stack.pop().unwrap();
+                    stack.push(num2 - num1);
+                },
+                "*" => {
+                    let num1 = stack.pop().unwrap();
+                    let num2 = stack.pop().unwrap();
+                    stack.push(num1 * num2);
+                },
+                "/" => {
+                    let num1 = stack.pop().unwrap();
+                    let num2 = stack.pop().unwrap();
+                    stack.push(num2 / num1);
+                },
+                _ => {
+                    stack.push(v.parse::<i32>().unwrap())
+                }
+
+            }
+
+        }
+        stack[0]
+    }
+}
+
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_eval_rpn() {
+        let tokens = vec!["10","6","9","3","+","-11","*","/","*","17","+","5","+"];
+        let tokens = tokens.iter().map(|&x| x.to_string()).collect::<Vec<String>>();
+        let res = Solution::eval_rpn(tokens);
+        assert_eq!(res, 22);
+    }
+}

+ 2 - 1
src/solutions/stack/mod.rs

@@ -1,3 +1,4 @@
 mod simplify_path;
 mod largest_rectangle_in_histogram;
-mod maximum_rectangle;
+mod maximum_rectangle;
+mod evaluate_reverse_polish_notation;