题目:
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.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7 " 3/2 " = 1 " 3+5 / 2 " = 5
基本思路: 把减法当成负数入栈,把正数的数值全部入栈,遇到*/运算先计算后将结果入栈,最后栈中的所有数值依次取出加法运算
1 public class Solution { 2 public int calculate(String s) { 3 4 if (s != null && s.length() != 0) { 5 Stack<String> stack = new Stack<>(); 6 int result = 0; 7 int i = 0; 8 while (i < s.length()) { 9 if(s.charAt(i) == ' ' || s.charAt(i) == '+'){ 10 i++; 11 } 12 else { 13 char tempChar = s.charAt(i); 14 StringBuffer buffer = new StringBuffer(); 15 if(tempChar == '*' || tempChar == '/'){ 16 int tempResult; 17 String firstVal = stack.pop(); 18 StringBuffer secondVal = new StringBuffer(); 19 int j = i+1; 20 while(s.charAt(j) == ' '){ 21 22 j++; 23 } 24 secondVal.append(s.charAt(j)); 25 while(j+1 != s.length() && s.charAt(j+1) > 47 && s.charAt(j+1) < 58){ 26 secondVal.append(s.charAt(++j)); 27 } 28 if(tempChar == '*') 29 tempResult = Integer.parseInt(firstVal) * Integer.parseInt(secondVal.toString()) ; 30 else { 31 tempResult = Integer.parseInt(firstVal) / Integer.parseInt(secondVal.toString()) ; 32 } 33 stack.push(Integer.toString(tempResult)); 34 if(j>i){ 35 i=j; 36 i++; 37 } 38 39 else { 40 i++; 41 } 42 } 43 44 else{ 45 buffer.append(s.charAt(i)); 46 if(i < (s.length()-1)){ 47 int j = i+1; 48 while(j < s.length() && s.charAt(j) == ' '){ 49 50 j++; 51 } 52 while(j != s.length() && s.charAt(j) > 47 && s.charAt(j) < 58){ 53 buffer.append(s.charAt(j++)); 54 } 55 if(j>i){ 56 i=j; 57 } 58 59 else { 60 i++; 61 } 62 }else{ 63 i++; 64 } 65 stack.push(buffer.toString()); 66 } 67 } 68 } 69 while(!stack.isEmpty() && stack.size() != 1){ 70 String secondVal = stack.pop(); 71 String firstVal = stack.pop(); 72 int tempResult = 0; 73 tempResult = Integer.parseInt(firstVal) + Integer.parseInt(secondVal.toString()); 74 stack.push(Integer.toString(tempResult)); 75 } 76 return Integer.parseInt(stack.pop()); 77 } 78 return 0; 79 80 81 } 82 }