[][src]Function leetcode_for_rust::cd0682_baseball_game::cal_points

pub fn cal_points(ops: Vec<String>) -> i32

Solutions

Approach 1: Stack

  • Time complexity: O(n)

  • Space complexity: O(n)

  • Runtime: 0ms

Memory: 2.6MB

impl Solution {
    pub fn cal_points(ops: Vec<String>) -> i32 {
        let mut stack: Vec<i32> = vec![];
        let mut sum = 0;

        for p in ops.into_iter() {
            match p.as_ref() {
                "+" => {
                    let top = stack.pop().unwrap();
                    let new_top = top + stack.last().unwrap();
                    stack.push(top);
                    stack.push(new_top);
                },
                "C" => { stack.pop(); },
                "D" => { stack.push(2 * stack.last().unwrap()); },
                _ => { stack.push(p.parse::<i32>().unwrap()); },
            }
        }

        for score in stack { sum += score; }

        sum
    }
}

Approach 2: Stack

  • Time complexity: O(n)

  • Space complexity: O(1)

  • Runtime: 0ms

Memory: 2.3MB

impl Solution {
    pub fn cal_points(ops: Vec<String>) -> i32 {
        let mut stack: Vec<i32> = vec![];
        let mut sum = 0;

        for p in ops.into_iter() {
            let mut score = 0;
            match p.as_ref() {
                "+" => { score = stack[stack.len()-1] + stack[stack.len()-2]; },
                "C" => {
                    sum -= stack.pop().unwrap();
                    continue;
                },
                "D" => { score = 2 * stack.last().unwrap(); },
                _ => { score = p.parse::<i32>().unwrap(); },
            }
            sum += score;
            stack.push(score);
        }
        sum
    }
}