第一周 leetcode 224. Basic Calculator(hard)

第一周 leetcode 224. Basic Calculator(hard)

题目描述:

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. 如果+,-,(就直接入操作符栈;
2.如果是数字,看操作符栈:
a.如果操作符栈顶是+、-,把该元素和数字栈顶元素进行相应运算并存入数字栈顶;
b.否则直接将该数字入栈;
3.如果是),直接把操作符栈栈顶元素给弹出,因为栈顶元素必然是(,然后将操作符栈和数字栈进行运算,直到不能运算为止;
4.注意数字位数可能大于1;
5.注意跳过空格;

代码:

class Solution {
public:
    int calculate(string s) {
        stack<int> operand; // 数字栈
        stack<char> ch;  // 操作符栈
        int n = 0;
        while(n < s.size()) { // 遍历字符串
            if (isspace(s[n])) {
                // 空格跳过
                n ++;
                continue;
            }
            if (isdigit(s[n])) {
                // 读数字
                int num = 0;
                while(n < s.size() && isdigit(s[n])) {
                    num = 10 * num + s[n] - '0';
                    n ++;
                }
                if (ch.empty() || ch.top() == '(') operand.push(num);
                else if (ch.top() == '+') {
                    num = operand.top() + num;
                    operand.pop();
                    ch.pop();
                    operand.push(num);
                }
                else {
                    num = operand.top() - num;
                    operand.pop();
                    ch.pop();
                    operand.push(num);
                }
            }
            else {
                if (s[n] == ')') {
                    ch.pop();
                    while (ch.size() && ch.top() != '(') {
                        int operand1 = operand.top(); operand.pop();
                        int operand2 = operand.top(); operand.pop();
                        if (ch.top() == '+') operand.push(operand1 + operand2);
                        else operand.push(operand2 - operand1);
                        ch.pop();
                    }
                }
                // 其他操作符,则直接入操作符栈
                else ch.push(s[n]);
                n ++;
            }
        }
        return operand.top();
    }
};

代码运行结果:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值