其他分享
首页 > 其他分享> > 224. 基本计算器

224. 基本计算器

作者:互联网

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/basic-calculator
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.Scanner;
import java.util.Stack;

class Solution {

    private void pushStack(Stack<Integer> stack, char sign, int num) {
        if (sign == '+') {
            stack.push(num);
        } else if (sign == '-') {
            stack.push(-num);
        } else if (sign == '*') {
            stack.push(stack.pop() * num);
        } else if (sign == '/') {
            stack.push(stack.pop() / num);
        }
    }

    private int[] solve(String str, int index) {
        Stack<Integer> stack = new Stack<>();
        int num = 0;
        char sign = '+';
        while (index < str.length() && str.charAt(index) != ')') {
            if (Character.isDigit(str.charAt(index))) {
                num = num * 10 + str.charAt(index++) - '0';
            } else if (str.charAt(index) == '(') {
                int[] next = solve(str, index + 1);
                index = next[0] + 1;
                num = next[1];
            } else if (str.charAt(index) == ' ') {
                index++;
            } else {
                pushStack(stack, sign, num);
                num = 0;
                sign = str.charAt(index++);
            }
        }
        pushStack(stack, sign, num);
        int sum = stack.stream().reduce(0, Integer::sum).intValue();
        return new int[]{index, sum};
    }

    public int calculate(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        return solve(s, 0)[1];
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            System.out.println(new Solution().calculate(in.nextLine()));
        }
    }
}

标签:基本,index,int,sign,num,str,计算器,224,stack
来源: https://www.cnblogs.com/tianyiya/p/15713449.html