[leetcode] 224. Basic Calculator 解题报告

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


思路: 最讨厌字符串处理的题目, 各种乱七八糟的数据. 自己写了一份代码, 处理完各种条件将近60行, 非常丑陋, 然后看了别人的代码, 发现一个极其优雅的写法, 非常佩服.

利用递归的思想如果碰到左括号就递归到下一层处理括号里的计算, 如果碰到右括号就返回当前一层的值; 

代码如下:

class Solution {
public:
    int calculate(string s) {
        int pos = 0;
        return cal("(" + s + ")", pos);
    }
    int cal(string s, int& pos)
    {
        int flag=1, num=0, i=pos, ans=0;
        while(i < s.size())
        {
            switch(s[i])
            {
                case '+': ans += flag*num; num = 0; flag=1; i++; break;
                case '-': ans += flag*num; num = 0; flag=-1; i++; break;
                case '(': pos = i+1; ans += flag*cal(s, pos); i=pos; break;
                case ')': pos = i+1; return ans + flag*num;
                case ' ': i++; break;
                default: num = num*10 + (s[i]-'0'); i++; break;
            }
        }
        return ans;
    }
};
参考: https://leetcode.com/discuss/83027/java-concise-fast-recursive-solution-with-comments-beats-61%25

你可能感兴趣的:(Math,LeetCode)