Fork me on GitHub

【数据结构】算法 Basic Calculator II 基本计算器

Basic Calculator II 基本计算器

给定一个字符串格式的算式,计算该式的值。只包含+-*/

Input: s = "3+2*2"
Output: 7
Input: s = " 3+5 / 2 "
Output: 5

思路

使用2个栈,nums存放数字,op存放符号;

 public int level(char c){
        switch (c){
            case '@':return -1;
            case '+':
            case '-':return 1;
            case '*':
            case '/':return 2;
        }
        return 0;
    }
    public int calc(char op,int a,int b){
        switch (op){
            case '+': return a+b;
            case '-': return a-b;
            case '*': return a*b;
            case '/': return a/b;
        }
        return 0;
    }

    public int calculate(String s) {
        Stack<Character> op = new Stack<>();
        Stack<Integer> num = new Stack<Integer>();
        s += "@";

        int n = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ') {
                continue;
            }
            if (level(s.charAt(i)) == 0) {
                n = n * 10 + (s.charAt(i) - '0');
                continue;
            }
            num.push(n);
            n = 0;
            while (!op.isEmpty() && level(s.charAt(i)) <= level(op.peek())) {
                int b = num.peek();
                num.pop();
                int a = num.peek();
                num.pop();
                num.push(calc(op.peek(), a, b));
                op.pop();
            }
            op.push(s.charAt(i));
        }
        return num.peek();
    }

Tag

stack

posted @ 2021-04-16 11:36  WilliamCui  阅读(72)  评论(0编辑  收藏  举报