[leetcode] 227. Basic Calculator II 解题报告

题目链接: https://leetcode.com/problems/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.


思路: 大致的思路就是将其分解成数和运算符, 然后运算完所有的乘除之后再运算加减, 但是在具体实施上还是需要点技巧. 刚开始我是先分解好数和运算符, 然后再使用双端队列, 如果碰到乘除,就运算; 碰到加减, 就符号和数依次存到队列中去. 然后运算完之后再从队首运算加减. 这样稍微有点麻烦, 因为连同运算符一起存储, 那么在运算的时候还需要考虑运算符, 这就是为什么保存运算符的话我要用双端队列的原因, 在运算乘除的时候我需要从队尾取数据, 但是在只剩加减运算的时候我就要从队首依次取数据了.

一种更为简便的方式是不保存运算符, 只以正负号的形式和数一起保存, 这样可以使用栈来操作.

代码如下:

class Solution {
public:
    int calculate(string s) {
        s += "+";
        stack st;
        char old = '+';
        for(int i = 0, left = 0; i < s.size(); i++)
        {
            if(isdigit(s[i]) || isspace(s[i])) continue;
            int val = stoi(s.substr(left, i-left));
            if(old=='+' || old=='-') st.push(old=='+'?val:-val);
            else st.top() = (old=='*'?st.top()*val:st.top()/val);
            old = s[i], left = i+1;
        }
        int ans = 0;
        while(!st.empty())
        {
            ans += st.top();
            st.pop();
        }
        return ans;
    }
};


你可能感兴趣的:(leetcode,string,stack,leetcode,string,stack)