[Leetcode] 227. 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.

思路

唉,自己写的代码总是很冗长。。。还是把网上这个精炼的算法贴在这里,帮大家一起分析一下吧:由于四个运算符可以分为两个优先级,所以我们可以考虑采用两次扫描:1)计算所有的*和/,并且将所有参与+和-运算的操作数(有可能是*和/的运算结果)都放在一个数组(栈)中;2)计算所有的+和-的结果。为了方便,这里使用了一个小技巧:如果是-,则将操作数取反,并存入数组中。这样的好处是所有的操作符都可以被认为是+,所以就不需要在数组中进行额外存储了。

代码

class Solution {
public:
    int calculate(string s) {
        s += "+";
        stack<int> st;
        char old = '+';
        int left = 0;
        for (int i = 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 ret = 0;
        while (!st.empty()) {
            ret += st.top();
            st.pop();
        }
        return ret;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值