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-negati ve integers 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
Note:do not use the eval
built-in library function.
Test instructions: Design a simple calculator, only positive, the operator is "+" "-" "()", input as a string, remove the useless space, the given calculation must be legal
Idea 1 (sequential solution): In order to combine parentheses and braces, it is considered that a pair () at both ends of the string is convenient to calculate, while considering that the number may be many bits, it is necessary to cut out each number and symbol, so design two stacks, respectively, to hold the numbers and operators, Then each time the right parenthesis is encountered, the calculation should be calculated as the normal calculation should be from left to right, so in the process of calculation, each one should be computed, instead of popping two bits for calculation.
Example: (2-1 + 2)
The correct calculation order for + 2-1 STACJ of the last char encounters an opening parenthesis at + 2
Incorrect calculation Order of 1 + 2 results after depositing A and then 2-a is obviously wrong need to understand
The number in the last Istack is the result.
Code Listing 1:
Public classSolution { Public intCalculate (String s) {if(s = =NULL|| S.length () = = 0) return0; S= "(" + S + ")"; Stack<Character> Cstack =NewStack<character>(); Stack<Integer> Istack =NewStack<integer>(); BooleanIsnum =false; intsum = 0; for(inti = 0; I < s.length (); i++){ if(S.charat (i) = = ") Continue; if(Character.isdigit (S.charat (i))) {Sum= Sum *10 + s.charat (i)-' 0 '; Isnum=true; Continue; }Else if(Isnum) {//consider the presence ((continuous non-numeric case, just press in the number onceistack.push (sum); Sum= 0; Isnum=false; } if(S.charat (i) = = ' + ' | | S.charat (i) = = '-' | | S.charat (i) = = ' (') {Cstack.push (S.charat (i)); }Else if(S.charat (i) = = ') '){ inttemp = 0;//each time the value in parentheses while(Cstack.peek ()! = ' (') {//until you can match the opening parenthesis intA =Istack.pop (); intc =Cstack.pop (); if(c = = ' + ')) {Temp+=A; }Else if(c = = '-')) {Temp-=A; }} Temp+ = Istack.pop ();//plus the number after the opening parenthesisIstack.push (temp); Cstack.pop (); } } returnIstack.pop (); }}
Train of thought 2 (suffix expression): The general method of calculation, the operation of parentheses into a non-parenthesized suffix expression, and then a stack to complete.
Code 2: (Just have ideas, code debug) ...
[Leetcode-java] Basic Calculator