[LeetCode]Basic Calculator II

本文介绍了一种使用栈数据结构实现的Java算法,用于解析和计算数学表达式。算法首先去除表达式中的空格,然后通过遍历字符并利用栈进行运算符和操作数的匹配,最终计算出表达式的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class Solution {
    public int calculate(String s) {
        Stack<String> stack = new Stack<String>();
        s = s.replace(" ", "");
        int length = s.length();
        int index = 0;
        if (s.charAt(0) <= '9' && s.charAt(0) >= '0')
            stack.push("+");
        while (index < length) {
            char ch = s.charAt(index);
            if (ch > '9' || ch < '0') {
                if (ch == '+' || ch == '-') {
                    stack.push(String.valueOf(ch));
                    index ++;
                } else {
                    int first = Integer.valueOf(stack.pop());
                    int tmp = index;
                    index = helper(s, index + 1);
                    int second = Integer.valueOf(s.substring(tmp + 1, index));
                    if (ch == '*') {
                        stack.push(String.valueOf(first * second));
                    } else {
                        stack.push(String.valueOf(first / second));
                    }
                }
            } else {
                int tmp = index;
                index = helper(s, index + 1);
                stack.push(s.substring(tmp, index));
            }
        }
        int result = 0;
        while (!stack.isEmpty()) {
            int tmp = Integer.valueOf(stack.pop());
            int positive = stack.pop().equals("+") ? 1 : -1;
            result += tmp * positive;
        }
        return result;
    }
    public int helper(String s, int index) {
        while(index < s.length() && s.charAt(index) <= '9' && s.charAt(index) >= '0') {
            index ++;
        }
        return index;
    }
}

 

转载于:https://www.cnblogs.com/vision-love-programming/p/5022848.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值