#227
Medium Algorithms Basic calculator ii
Math String Stack
46.7% acceptance
Jan 12, 2026
6584
950
Given a string s which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn calculate(s: String) -> i32 {
let mut stack = vec![];
let mut num = 0;
let mut op = '+';
for (i, ch) in s.chars().enumerate() {
if ch.is_ascii_digit() {
num = num * 10 + (ch as i32 - '0' as i32);
}
if (!ch.is_ascii_digit() && ch != ' ') || i == s.len() - 1 {
match op {
'+' => stack.push(num),
'-' => stack.push(-num),
'*' => {
let last = stack.pop().unwrap();
stack.push(last * num);
}
'/' => {
let last = stack.pop().unwrap();
stack.push(last / num);
}
_ => {}
}
op = ch;
num = 0;
}
}
stack.iter().sum()
}
}