LeetCode224: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:
这里写图片描述
Note: Do not use the eval built-in library function.

想了半天也没想出怎么做,倒是发现了表达式求值可以通过后缀式来求解,但是这涉及到了两个过程:

  1. 将表达式的中缀式转成后缀式
  2. 遍历后缀式求表达式值

可是这两步用代码实现少说得上百行代码,明显不适合在leetcode中使用,最终在discuss中看到了一种解法,说明也比较详细,不过是用java编写的,但好歹还能看明白。只是不明白是怎么想出这种解法的。

Simple iterative solution by identifying characters one by one. One important thing is that the input is valid, which means the parentheses are always paired and in order. Only 5 possible input we need to pay attention:

  1. digit: it should be one digit from the current number
  2. ‘+’: number is over, we can add the previous number and start a new
    number
  3. ‘-‘: same as above
  4. ‘(‘: push the previous result and the sign into the stack, set
    result to 0, just calculate the new result within the parenthesis.
  5. ‘)’: pop out the top two numbers from stack, first one is the sign
    before this pair of parenthesis, second is the temporary result
    before this pair of parenthesis. We add them together.

Finally if there is only one number, from the above solution, we haven’t add the number to the result, so we do a check see if the number is zero.

runtime:16ms

class Solution {
public:
    int calculate(string s) {
        stack<int> st;
        int number=0;
        int result=0;
        int sign=1;
        for(int i=0;i<s.size();i++)
        {
           if(isdigit(s[i]))
                number=10*number+s[i]-'0';
            else if(s[i]=='+')
            {
                result+=sign*number;
                number=0;
                sign=1;
            }
            else if(s[i]=='-')
            {
                result+=sign*number;
                number=0;
                sign=-1;
            }
            else if(s[i]=='(')
            {
                st.push(result);
                st.push(sign);
                result=0;
                sign=1;
            }
            else if(s[i]==')')
            {
                result+=sign*number;
                sign=st.top();
                st.pop();
                result=sign*result+st.top();
                st.pop();
                number=0;
            }
        }
        if(number!=0) result+=sign*number;

        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值