227. Basic Calculator II
Problem description:
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 the eval built-in library function.
Solution:
The idea is to use stack
to store every signed numbers in it. One thing to notice is that we need to use a variable to denote positive of first digit. Whenever we reach to second operator
, we can definitely push the previous result into stack. For example:
-1+2 : the sign was initially -
. When we meet second operator +
, we can push -1
into the stack. then set sign to +
Therefore, we need a stack
to store calculated value. sign
to store a sign that waited to be calculated. tmp
is current value.
Example: 3+5/2
1
2
3
4
5
6
7 init-> 0 -> 1 -> 2 -> 3 -> 4(reach to end)
stack: []-> []-> [3]->[3]->[3,5]->[3,5] become [3,2] after calculation
sign: + -> + -> + -> + -> / -> 2
tmp: 0 -> 3 -> 0 -> 5 -> 0 -> 0
Then, just add up value in stack.
3+2 = 5
1 | # when we reach to second operator, calculate result and push to stack |
1 | class Solution { |
time complexity: O(n)
space complexity: O(n)