Skip to main content

rustgym/leetcode/
_682_baseball_game.rs

1struct Solution;
2
3impl Solution {
4    fn cal_points(ops: Vec<String>) -> i32 {
5        let mut stack: Vec<i32> = vec![];
6        for s in ops {
7            match s.as_ref() {
8                "C" => {
9                    stack.pop();
10                }
11                "D" => {
12                    let top = stack.pop().unwrap();
13                    let double = top * 2;
14                    stack.push(top);
15                    stack.push(double);
16                }
17                "+" => {
18                    let b = stack.pop().unwrap();
19                    let a = stack.pop().unwrap();
20                    let plus = a + b;
21                    stack.push(a);
22                    stack.push(b);
23                    stack.push(plus);
24                }
25                _ => {
26                    stack.push(s.parse::<i32>().unwrap());
27                }
28            }
29        }
30        stack.iter().sum()
31    }
32}
33
34#[test]
35fn test() {
36    let ops: Vec<String> = vec_string!["5", "2", "C", "D", "+"];
37    assert_eq!(Solution::cal_points(ops), 30);
38    let ops: Vec<String> = vec_string!["5", "-2", "4", "C", "D", "9", "+", "+"];
39    assert_eq!(Solution::cal_points(ops), 27);
40}