Leetcode 224 Basic Calculator, leetcodecalculator

Source: Internet
Author: User

Leetcode 224 Basic Calculator, leetcodecalculator
1. Problem Description

Calculates the value of a string expression. The expression only contains (,), +,-, spaces, and non-negative integers. For example:
"1 + 1" = 2
"2-1 + 2" = 3
"(1 + (4 + 5 + 2)-3) + (6 + 8)" = 23
Link: https://leetcode.com/problems/basic-calculator/

2. methods and ideas 2.1 using suffix expressions for Computation

One idea is to convert the infix expression to the suffix expression for calculation according to the conventional method. The conversion process is as follows:
Traverse the string in sequence and perform the following operations.

class Solution {public:    int GetNum(string poststr,int *i)    {        int tmp =0;        while(poststr[(*i)] >= '0' && poststr[(*i)] <= '9')        {            tmp = tmp*10 + ( poststr[(*i)] - '0');            (*i) ++;        }        return tmp;    }    int postcal(string poststr)    {        stack<int> s;        int i,a,b,tmp =0;        for(i=0; i < poststr.length(); i++)        {            switch(poststr[i])            {                case ' ':                    continue;                case '+':                    b = s.top(); s.pop();                    a = s.top(); s.pop();                    s.push(a+b);                    break;                case '-':                    b = s.top(); s.pop();                    a = s.top(); s.pop();                    s.push(a-b);                    break;                default:                    s.push(GetNum(poststr,&i));            }        }        return s.top();    }    int calculate(string s) {        int re =0,tmp = 0;        stack<char> num;        string poststr="";        for(int i=0; i < s.length(); i++)        {            switch(s[i])            {                case '(':                    num.push(s[i]);                     break;                case ' ':                    continue;                case ')':                    poststr += " ";                    while(num.top() != '(')                    {                        poststr += num.top();                        num.pop();                    }                    num.pop();                    break;                case '+':                case '-':                    poststr += " ";                    while(!num.empty() && num.top() != '(')                    {                        poststr +=num.top();                        num.pop();                    }                    num.push(s[i]);                    break;                default:                    poststr += s[i];            }            }        poststr += " ";        while(!num.empty())        {            poststr += num.top();            num.pop();        }        //cout<<poststr<<endl;        return postcal(poststr);     }};

However, this method times out and is dizzy. You have to take a good look and see if there are any optimizations !!!

2.2 Expression simplification

Since the expression only contains parentheses and addition and subtraction operations, we can simplify the expression by adding and subtraction rules and then evaluate the value.
  

class Solution {public:    int calculate(string s) {        stack<int> num;        num.push(1);        char op = '+';                long re = 0;        for (int i=0; i<s.length(); i++) {            switch(s[i]) {                case ' ':                    break;                case '+':                case '-':                    op = s[i];                    break;                case '(':                    num.push(num.top() * (op == '-' ? -1 : 1));                    op = '+';                    break;                case ')':                    num.pop();                    break;                default:                    int tmp = 0;                    while (  s[i] >= '0' && s[i] <= '9') {                        tmp = tmp * 10 + s[i] - '0';                        i++;                    }                    i--;                    re += (op == '-'?-1:1)*num.top()*tmp;            }        }        return re;    }};

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.