Title Link: https://leetcode.com/problems/basic-calculator/
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-negative 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.
Ideas:
Use the stack to save the operand, operator, you should pay attention to the case of the right parenthesis.
Algorithm:
Public int Calculate(String s) {stack<string>operator=NewStack<string> (); Stack<integer> nums =NewStack<integer> (); s = S.replace (" ","");intCurnum =0;//Consecutive characters are numbers to be combined into a number for(inti =0; I < s.length (); i++) {CharOP = S.charat (i);if(Character.isdigit (OP)) {//Current is digitalCurnum = Integer.parseint (op +""); while(i +1< S.length () && character.isdigit (S.charat (i +1))) {//Subsequent characters are also numbers, combined into a number CharNextnum = S.charat (i +1); Curnum = Curnum *Ten+ integer.parseint (Nextnum +""); i++; }//An operand finishes processing if(!operator. IsEmpty () && nums.size () >=1&& (operator. Peek (). Equals ("+") ||operator. Peek (). Equals ("-"))) {//If the operand stack has operands, and //Operation Fu Yi has +/-, the current number and the number in the stack are processed accordinglyString tmp =operator. Pop ();if(Tmp.equals ("-")) {intFirst = Nums.pop (); Nums.push (First-curnum); }Else{Nums.push (Nums.pop () + curnum); } }Else{Nums.push (curnum); } }Else{//The current character is an operator if(OP = =' + '|| OP = ='-'|| OP = =' (') {operator. Push (OP +""); }Else if(OP = =' ) ') {if(operator. Peek (). Equals ("(")) {//If the brackets are eliminated, the operation preceding the opening parenthesis is processed, that is, processing //1+ (4) in + calculation operator. Pop ();if(!operator. IsEmpty () && nums.size () >=2&& (operator. Peek (). Equals ("+") ||operator. Peek (). Equals ("-")) {String TMP =operator. Pop ();if(Tmp.equals ("-")) {intFirst = Nums.pop ();intSecond = Nums.pop (); Nums.push (Second-first); }Else{Nums.push (Nums.pop () + Nums.pop ()); } } }Else{operator. Push (")"); } } } }returnNums.pop (); }
"Leetcode" Basic Calculator