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. Assume that the given expression was always valid. Some examples: "3+2*2" = 7 "3/2" = 1 "3+5/2" = 5note:do not use the Eval built-in library function.
Test instructions: Evaluation
Public class solution { public int calculate (String s) { int digt=0; char op= ' + '; int res=0; int n=s.length (); stack< Integer> stack=new stack<> (); for (int i =0;i<n;i++) { if (s.charAt (i) >= ' 0 ' && s.charat (i) <= ' 9 ') digt=digt*10+s.charat (i)-' 0 '; int temp=digt; if (S.charat (i) = = ' + ' | | s.charat (i) = = '-' | | s.charat (i) = = ' * ' | | s.charat (i) = = '/' | | i==n-1) { Switch (OP) { case ' + ': Stack.push (digt);break; case '-': Stack.push (-digt); case ' * ': Stack.push (Stack.pop () *digt);break; case '/': Stack.push (Stack.pop ()/ digt); break; } op=s.charat (i); digt=0; } } while (!stack.empty ()) { res+=stack.pop (); } return res; }}
Ps:
Stack
Define a temp stack to hold the operand of the operation (including the intermediate operation value)
D to save the last operand
Op to save the last operand, not the current operand
Traversing strings
-
-
If it is an operator
-
+: Depositing +d stack
-
-: Save-D to < Span style= "margin:0px;padding:0px;" >stack
-
*: Stack The top value and the multiply of D accumulate into the stack
-
/: Stack Top Value in addition to D is deposited stack
The spatial complexity is O (n), and the time complexity is O (n). It is important to note that each time the operand is in the stack is the next operator, a bit similar to the delay operation, so the most recent operand and operator need to be stored in two additional variables. And a little trick, if we add a ' + ' operator to the front and back of the string, we can reduce the complexity of the code. such as "1+2*3" modified to "+1+2*3+".
Leetcode 227. Basic Calculator II Java language