[][src]Function leetcode_for_rust::cd0224_basic_calculator::calculate

pub fn calculate(s: String) -> i32

Solutions

Approach 1: Stack

  • Time complexity: O(n)

  • Space complexity: O(n)

  • Runtime: 0ms

Memory: 2.9MB

impl Solution {
    pub fn calculate(s: String) -> i32 {
        let mut stack = vec![];
        let mut operand = 0;
        let mut result = 0;
        let mut sign = 1;

        stack.push(sign);
        for ch in s.chars() {
            match ch {
                '0'...'9' => {
                    operand = 10 * operand + (ch as u8 - '0' as u8) as i32;
                },
                '(' => {
                    stack.push(sign);
                },
                ')' => {
                    stack.pop();
                },
                '+' | '-' => {
                    result += sign * operand;
                    operand = 0;
                    sign = stack.last().unwrap() * if ch == '+' { 1 } else { -1 };
                },
                _ => {},
            }
        }
        result + (sign * operand)
    }
}