本题也不难,最开始我用deque的方法做出了,但是更加费空间,所以看了下答案,答案思路一致,但是简化的更好:
- 遇到
*和/的时侯,进行计算 遇到
+和-,推进Stack<Integer>中- 根据之前的operator,来决定存正还是负
空间复杂度:
- 时间复杂度:
代码远比描述更好懂,直接上代码了:
class Solution {public int calculate(String s) {int result = 0;Stack<Integer> stack = new Stack<>();char operator = '+';int curr = 0;for (int i = 0; i < s.length(); ++i) {char ch = s.charAt(i);if (ch == ' ') {continue;}else if (ch >= '0' && ch <= '9') {curr = curr * 10 + (ch - '0');}else {if (operator == '+') {stack.push(curr);}else if (operator == '-') {stack.push(-curr);}else if (operator == '*') {stack.push(stack.pop() * curr);}else if (operator == '/') {stack.push(stack.pop() / curr);}curr = 0;operator = ch;}}if (operator == '+') {stack.push(curr);}else if (operator == '-') {stack.push(-curr);}else if (operator == '*') {stack.push(stack.pop() * curr);}else if (operator == '/') {stack.push(stack.pop() / curr);}while (!stack.isEmpty()) {result += stack.pop();}return r
