leetcode Basic Calculator II


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.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5

Note: Do not use the eval built-in library function.

Credits:

Special thanks to @ts for adding this problem and creating all test cases.


思路:

由中缀表达式得到后缀表达式,再计算后缀表达式;

后缀表达式中遇到运算符时,分别得到栈顶的2个整数,再进行计算后结果入栈;

对于 +,-,*,/,( 打表入栈的优先级:若栈顶元素优先级高,则出栈,直到栈顶优先级低于插入的符号或者栈顶为'(‘。再把当前符号插入栈中。

用long long类型处理溢出;

class Solution {
public:
    int k = 0;
    char sign[6] = {'+','-','*','/','#','('};
    int cmp[6][6]={
                     {1,1,0,0,1,0},
                     {1,1,0,0,1,0},
                     {1,1,1,1,1,0},
                     {1,1,1,1,1,0},
                     {0,0,0,0,1,0},
                     {1,1,1,1,1,0}
                   };
    int search_sign(char s)
    {
        int i = 0;
        for(i = 0;i<6;i++)
        {
            if(sign[i] == s)
                return i;
        }
    }
    string int_to_string(long long n)
    {
        char s[100];
        memset(s,0,sizeof(s));
        sprintf(s,"%lld",n);
        string ss = "";
        ss = ss+s;
        return ss;
    }

    bool is_num(string s)
    {
        if(s[0]>= '0' && s[0]<='9')
        {
            return true;
        }
        else
            return false;
    }
    int calculate(string s) {
        stack<char>  sta;
        vector<string> last;//后缀表达式
        sta.push('#');
        string s_temp;
        int i = 0;
        long long  a,b;



        for(i = 0;i<s.length();i++)
        {
            //cout<<"i: "<<i<<"len: "<<s.length()<<endl;
            if(s[i] == ' ')
            continue;
            else if(s[i] >= '0'  && s[i] <= '9')
            {
                long long temp = s[i]-'0';
                i++;
                while(i<s.length() && s[i] >='0' && s[i] <='9' )
                {
                    temp = temp * 10 + s[i]-'0';
                    i++;
                }

               i--;
               last.push_back(int_to_string(temp));
            }
            else
            {
                if(s[i] == '(')
                  {
                      sta.push(s[i]);
                  }
                else if(s[i] == ')')
                  {
                      while(!sta.empty())
                      {
                          if(sta.top()!='(')
                          {
                              s_temp = "";
                              s_temp = s_temp+sta.top();
                              last.push_back(s_temp);
                              sta.pop();
                          }
                          else
                          {
                              sta.pop();
                              break;
                          }
                      }
                  }
                else
                {
                    //+ ,-,*,/
                    while(!sta.empty())
                    {
                        if(sta.top()!='(' && cmp[search_sign(sta.top())][search_sign(s[i])] == 1)
                        {
                            s_temp = "";
                            s_temp = s_temp+sta.top();
                            last.push_back(s_temp);
                            sta.pop();
                        }
                        else
                            break;
                    }
                    sta.push(s[i]);
                }


            }
        }


        stack<long long> num;
        long long  sum = 0;
        for(i = 0;i<last.size();i++)
        {
            if(is_num(last[i]))
            {

                num.push(atoll(last[i].c_str()));
            }
            else
            {
              a = num.top();
              num.pop();
              b = num.top();
              num.pop();
              switch(last[i][0])
                  {
                      case '+' : sum =  a+b; break;
                      case '-' : sum =  b-a; break;
                      case '*' : sum =  b*a; break;
                      case '/' : sum =  b/a; break;
                  }
              num.push(sum);
            }

        }
        while(!sta.empty())
        {
            if(num.size() < 2)
                break;
            a = num.top();
            num.pop();
            b = num.top();
            num.pop();
            //cout<<a<<" "<<b<<sta.top()<<endl;
            switch(sta.top())
                  {
                      case '+' : sum =  a+b;  num.push(sum);break;
                      case '-' : sum =  b-a;  num.push(sum);break;
                      case '*' : sum =  b*a;  num.push(sum);break;
                      case '/' : sum =  b/a;  num.push(sum);break;
                      case '#' : break;
                  }

            sta.pop();

        }

        return num.top();

    }
};


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值