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: 7Example 2:
Input: " 3/2 " Output: 1Example 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.
基本计算器II。
题意跟版本一基本一样,多了乘法和除法的操作但是省去了括号,同时需要skip中间遇到的空格。有了乘法和除法的话,计算就需要有优先级。思路依然是用stack,也是按字符遍历input,遇到乘号和除号的时候需要把栈顶元素pop出来,先计算乘法/除法,把计算后的结果再放入栈内。如果遇到一个字符既不是数字也不是空格,那么一定是一个运算符。如果遇到的是加号或者减号,则把他变成栈顶元素的正号/负号;如果是乘号/除号的话则进行计算,把计算结果入栈。在这道题中,运算符号是不入栈的,最后从stack弹出元素的时候,所有元素之间做的只有加法。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public int calculate(String s) { 3 Stack<Integer> stack = new Stack<>(); 4 int res = 0; 5 char sign = '+'; 6 int num = 0; 7 for (int i = 0; i < s.length(); i++) { 8 if (Character.isDigit(s.charAt(i))) { 9 num = s.charAt(i) - '0'; 10 while (i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))) { 11 num = num * 10 + s.charAt(i + 1) - '0'; 12 i++; 13 } 14 } 15 // 不是数字不是空格又不是最后一个字符,那么一定是一个运算符号 16 // 最后一个字符有可能是一个单独的数字,需要特别处理 17 if (!Character.isDigit(s.charAt(i)) && s.charAt(i) != ' ' || i == s.length() - 1) { 18 if (sign == '+') { 19 stack.push(num); 20 } 21 if (sign == '-') { 22 stack.push(-num); 23 } 24 if (sign == '*') { 25 stack.push(stack.pop() * num); 26 } 27 if (sign == '/') { 28 stack.push(stack.pop() / num); 29 } 30 sign = s.charAt(i); 31 num = 0; 32 } 33 } 34 35 for (int i : stack) { 36 res += i; 37 } 38 return res; 39 } 40 }
相关题目