227 Basic Calculator II
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:
Example 2:
Example 3:
Note:
You may assume that the given expression is always valid.
Do not use the
eval
built-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?