[LeetCode] 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.

 

这道题让我们实现一个基本的计算器来计算简单的算数表达式,而且题目限制了表达式中只有加减号,数字,括号和空格,没有乘除,那么就没啥计算的优先级之分了。于是这道题就变的没有那么复杂了。我们需要一个一维的符号数组来记录加减号,然后我们开始遍历字符串表达式,如果遇到的是数字,则从符号数组中取出最后一个符合和数字运算后更新结果,如果遇到右括号,则移除一个符号,如果遇到的不是空格,即有可能是加减号或是左括号,则符号数组中加1或-1,做个判断,如果是负号,加个-1,其他情况加1。代码如下:

 

class Solution {
public:
    int calculate(string s) {
        int res = 0;
        vector<int> sign(2, 1);
        for (int i = 0; i < s.size(); ++i) {
            char c = s[i];
            if (c >= '0') {
                int num = 0;
                while (i < s.size() && s[i] >= '0') {
                    num = 10 * num + s[i++] - '0';
                }
                res += sign.back() * num;
                sign.pop_back();
                --i;
            }
            else if (c == ')') sign.pop_back();
            else if (c != ' ') sign.push_back(sign.back() * (c == '-' ? -1 : 1));
        }
        return res;
    }
};

 

参考资料:

https://leetcode.com/discuss/39532/easy-18-lines-c-16-lines-python

https://leetcode.com/discuss/39509/ac-c-solution-with-two-stacks

 

LeetCode All in One 题目讲解汇总(持续更新中...)

你可能感兴趣的:(LeetCode)