[Leetcode] Basic Calculator

Source: Internet
Author: User

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.

A very detailed explanation: http://www.geeksforgeeks.org/expression-evaluation/is more difficult than this problem

The idea is that there are two stacks, one stored number and one symbol. If a number is encountered, it is stored directly to the digital stack, and if a symbol is encountered, there are several cases:

1. The current symbol has a higher priority than the previous symbol, such as * above +, then directly into the stack

2. If the current symbol is lower than the previous, then all the existing symbols in the stack must be completed before the current symbol is pushed

3. The current symbol is "(", Direct push

4. The current symbol is ")", it is necessary to all "(" the previous symbol all finished

This problem only "+" and "-" number, do not judge the priority of the symbol.

1 classSolution {2  Public:3     intCalculatestrings) {4stack<int>Stk_val;5stack<Char>Stk_op;6         intres =0, TMP;7          for(inti =0; I <= s.length (); ++i) {8             //Number of operands9             if(I < s.length () &&isdigit (S[i])) {Tenres =0; One                  while(I < s.length () &&isdigit (S[i])) { ARes *=Ten; -Res + = s[i++]-'0'; -                 } the Stk_val.push (res); -             } -             //operator -             if(i = = s.length () | | s[i] = ='+'|| S[i] = ='-'|| S[i] = =')') { +                  while(!stk_op.empty () && stk_op.top ()! ='(') { -TMP =stk_val.top (); + Stk_val.pop (); A                     if(Stk_op.top () = ='+') Stk_val.top () + =tmp; at                     Else if(Stk_op.top () = ='-') Stk_val.top ()-=tmp; - Stk_op.pop (); -                 } -                 if(i = = S.length ()) Break; -                 Else if(S[i] = =')') Stk_op.pop (); -                 ElseStk_op.push (S[i]); in}Else if(S[i] = ='(') { - Stk_op.push (S[i]); to             } +         } -         returnstk_val.top (); the     } *};

There is a same problem on the Lintcode, but the operators contain not only "+", "-", but also "*" and "/", but do not have to parse the operands themselves.

Expression Evaluation

Given An expression string array, return the final result of this expression

2*6-(23+7)/(1+2)for the expression, input is

[  "2", "*", "6", "-", "(",  "23", "+", "7", ")", "/",  (", "1", "+", "2", ")"],

Return2

Note

The expression contains only,,,,, integer + - * / ( , ) .

1 classSolution {2  Public:3     /**4 * @param expression:a vector of strings;5 * @return: An integer6      */7     intCalulate (intAintBConst string&op) {8         if(OP = ="+")returnA +b;9         Else if(OP = ="-")returnAb;Ten         Else if(OP = ="*")returnAb; One         Else returnAb; A     } -     BOOLIsOK (Const string&AMP;OP1,Const string&OP2) { -         if(OP1 = ="*"|| OP1 = ="/"|| OP2 = =")")return true; the         Else returnOP2 = ="+"|| OP2 = ="-"; -     } -     intEvaluateExpression (vector<string> &expression) { -         //Write your code here +         if(Expression.empty ())return 0; -stack<int>Stk_val; +stack<string>Stk_op; A          for(inti =0; I <= expression.size (); ++i) { at             if(I < Expression.size () && isdigit (expression[i][0])) { - Stk_val.push (Atoi (Expression[i].c_str ())); -}Else if(i = = expression.size () | | expression[i]! ="(") { -                  while(!stk_op.empty () && stk_op.top ()! ="("  -&& (i = = expression.size () | |IsOK (Stk_op.top (), Expression[i])) { -                     intTMP =stk_val.top (); in Stk_val.pop (); -Stk_val.top () =calulate (Stk_val.top (), TMP, Stk_op.top ()); to Stk_op.pop (); +                 } -                 if(i = = Expression.size ()) Break; the                 Else if(Expression[i] = =")") Stk_op.pop (); *                 ElseStk_op.push (Expression[i]); $}Else {Panax Notoginseng Stk_op.push (Expression[i]); -             } the         } +         returnstk_val.top (); A     } the};

[Leetcode] Basic Calculator

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.