leetcode 224. Basic Calculator

来源:互联网 发布:js如何获取classname 编辑:程序博客网 时间:2024/05/16 08:35

224. 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-negative integers and empty spaces .

You may assume that the given expression is 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.


class Solution {public:    int calculate(string s)     {        stack<int> value;            stack<char> fuhao;        for (int i = 0; i < s.size(); i++)        {            if (s[i] == ' ')                continue;            else if (s[i] == '+' || s[i] == '-' || s[i] == '(')                fuhao.push(s[i]);            else if (s[i] >= '0' && s[i] <= '9')  //压入数字            {                int ii = i;                    while (s[ii] >= '0' && s[ii] <= '9')                    ii++;                value.push( atoi(s.substr(i, ii - i).c_str()) );                i = ii - 1;            }            else if (s[i] == ')')   //遇到')'需要处理了            {                stack<int> value_temp;                value_temp.push(value.top());                value.pop();                stack<char> fuhao_temp;                                while (fuhao.top() != '(')                {                    value_temp.push(value.top());                    value.pop();                      fuhao_temp.push(fuhao.top());                    fuhao.pop();                }                fuhao.pop();                value.push(getvalue(value_temp, fuhao_temp));            }         }                stack<int> value_temp;  //需要reverse栈,因为计算填入是反的。        while (!value.empty())        {            value_temp.push(value.top());            value.pop();        }        stack<char> fuhao_temp;        while (!fuhao.empty())        {            fuhao_temp.push(fuhao.top());            fuhao.pop();        }                return getvalue(value_temp, fuhao_temp);    }        int getvalue(stack<int> &value, stack<char> &fuhao)    {        while (!fuhao.empty())        {            int a = value.top();             value.pop();            int b = value.top();             value.pop();            if (fuhao.top() == '+')                value.push(a + b);            else                value.push(a - b);            fuhao.pop();        }        return value.top();    }};


原创粉丝点击