LC 227. 基本计算器 II

题目描述

给你一个字符串表达式s,请你实现一个基本计算器来计算并返回它的值。

整数除法仅保留整数部分。

样例
输入:s = "3+2*2"
输出:7

算法

栈模拟
时间复杂度

O ( n ) O(n) O(n)

Java 代码
class Solution {

    int[] stk1;
    char[] stk2;
    int tt1 = 0, tt2 = 0;

    int solve(int a, int b, char op) {
        int ans = 0;
        switch (op) {
            case '+' : ans = a + b; break;
            case '-' : ans = a - b; break;
            case '*' : ans = a * b; break;
            case '/' : ans = a / b; break;
        }
        return ans;
    }

    public int calculate(String s) {

        int len = s.length();
        stk1 = new int [2 * len];
        stk2 = new char [2 * len];

        int begin = 0;
        if (s.charAt(0) == '-') {
            stk1[ ++ tt1] = 0;
            stk2[ ++ tt2] = '-';
            begin = 1;
        }

        int flag = 0;
        int nega = 0;
        for (int i = begin; i < len; i ++ ) {
            char c = s.charAt(i);

            if (c == ' ') continue;
            if (c >= '0' && c <= '9') {
                int num = 0;
                int idx = i;
                while (idx < len && s.charAt(idx) >= '0' && s.charAt(idx) <= '9') {
                    num = num * 10 + (s.charAt(idx) - '0');
                    idx ++ ;
                }
                i = idx - 1;
                if (nega == 1) {
                    stk1[ ++ tt1] = -num;
                    nega = 0;
                } else {
                    stk1[ ++ tt1] = num;
                }
                // 高优先级运算符优先运算
                if (flag == 1) {
                    int a = stk1[tt1 -- ];
                    int b = stk1[tt1 -- ];
                    char o = stk2[tt2 -- ];
                    int ans = solve(b, a, o);
                    stk1[ ++ tt1] = ans;
                    flag = 0;
                }
            } else {
                
                if (c == '*' || c == '/') {
                    flag = 1;
                    stk2[ ++ tt2] = c;
                }
                else if (c == '-') {
                    nega = 1;
                    stk2[ ++ tt2] = '+';
                }
                else
                    stk2[ ++ tt2] = c;
            }
        }
        if (tt1 > 1) {
            while (tt2 > 0) {
                int a = stk1[tt1 -- ];
                int b = stk1[tt1 -- ];
                char o = stk2[tt2 -- ];
                int ans = solve(b, a, o);
                stk1[ ++ tt1] = ans;
            }
        }
        return stk1[tt1];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水能zai舟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值