227 Basic Calculator II

1. Question

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers,+,-,*,/operators and empty spaces. The integer division should truncate toward zero.

Example 1:

Input: "3+2*2"
Output: 7

Example 2:

Input: " 3/2 "
Output: 1

Example 3:

Input: " 3+5 / 2 "
Output: 5

Note:

  • You may assume that the given expression is always valid.

  • Do not use theevalbuilt-in library function.

2. Implementation

(1) Stack

思路: 用两个stack,一个是nums,存放数字,一个是operators, 存放运算符号,注意计算时,如果operators顶部的运算符的计算优先级高于当前的运算符,需要先将顶部的运算符出栈,然后计算结果

3. Time & Space Complexity

(1) Stack: 时间复杂度O(n), 空间复杂度O(n)

Last updated

Was this helpful?