Topic:
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open(and closing parentheses), the Plus+or minus sign-,non-negativeIntegers and empty spaces.
Assume that the given expression was always valid.
Some Examples:
"1 + 1" = 2 "2-1 + 2" = 3 "(1+ (4+5+2)-3) + (6+8)" = 23
Answer:
The common practice for this type of question is to turn to a suffix expression and then calculate it based on the inverse Polish calculation method. But the problem is special, because it only adds and subtract, we can use the simple parentheses to calculate, such as "1-(4-6) +5) +3"
In this expression, a total of 1 2 4 6 5 3 of these numbers, we just have to figure out what the final symbol of these numbers, the final symbol depends on the number before the symbol and all the left parenthesis before the number of the symbol before the score, such as 2:+1* (-1) 4:+1* (-1) * (-1) 5:+1* (-1) * (-1) Knowing this, you should be able to read the code.
Code:
public static int calculate (String s) {char[] Array=s.tochararray (); Stack<integer> stack=new stack<> (); int result=0; int sign=1; Stack.push (1); for (int i=0;i<array.length;i++) {if (Character.isdigit (Array[i])) {int num=array[i]-' 0 ', int j=i+1; while (j< Array.length&&character.isdigit (Array[j]) {num=10*num+array[j]-' 0 '; j + +;} result+=sign*stack.peek () *num; i=j-1;//j front equals i+1} else if (array[i]== ' + ') sign=1; else if (array[i]== '-') sign=-1; else if (array[i]== ')///record the symbol before the opening parenthesis, because it affects all operators in parentheses {Stack.push (Sign*stack.peek ()); sign=1;} else if (array[i]== ') ')//ensure that the symbol that is pressed into the stack before the opening parenthesis does not affect the subsequent operations Stack.pop () that are not in parentheses; else {;//spaces do not operate} } return result; }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
LeetCode224 basiccalculator Java