Basic Calculator
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.
Two points:
1, without parentheses, sequential execution
2, in parentheses, first execute the parentheses in the
Two stacks:
A storage operand, each time the stack to note that if the operation Fu Yi the top element is ' + '/'-', it needs to be calculated immediately.
A storage operator (including parentheses), each time ') ', is constantly doing a stack calculation and then into the stack until the ' (', indicating that the current parentheses are calculated.
classSolution { Public: intCalculatestrings) {stack<int>num; Stack<int>op; inti =0; while(I <s.size ()) { while(I < S.size () && s[i] = =' ') I++; if(i = =s.size ()) Break; if(S[i] = ='+'|| S[i] = ='-'|| S[i] = ='(') {Op.push (s[i]); I++; } Else if(S[i] = =')') { while(Op.top ()! ='(') {//calculation within parentheses intN2 =Num.top (); Num.pop (); intN1 =Num.top (); Num.pop (); if(Op.top () = ='+') Num.push (N1+n2); ElseNum.push (N1-n2); Op.pop (); } op.pop (); while(!op.empty () && op.top ()! ='(') { intN2 =Num.top (); Num.pop (); intN1 =Num.top (); Num.pop (); if(Op.top () = ='+') Num.push (N1+n2); ElseNum.push (N1-n2); Op.pop (); } I++; } Else { intn =0; while(I < S.size () && S[i] >='0'&& S[i] <='9') {n= NTen+ (s[i]-'0'); I++; } num.push (n); while(!op.empty () && op.top ()! ='(') { intN2 =Num.top (); Num.pop (); intN1 =Num.top (); Num.pop (); if(Op.top () = ='+') Num.push (N1+n2); ElseNum.push (N1-n2); Op.pop (); } } } returnNum.top (); }};
"Leetcode" 224. Basic Calculator