227. 基本计算器 II

227. 基本计算器 II

class Solution {
    public int calculate(String s) {
        Stack<Integer> stack = new Stack<Integer>();//例如 3 + 5 / 2 + 4 * 3
        int l = s.length();
        int num = 0;
        char flag = '+';//记录符号
        for(int i=0;i<l;i++){
            if(Character.isDigit(s.charAt(i))){
                num = num * 10 + (s.charAt(i)-'0');//记录数字
            }
            if(!Character.isDigit(s.charAt(i))&&s.charAt(i)!=' '||i==l-1){//出现符号或者遍历到最后,需要将数据压入栈内的情况
                switch (flag){
                    case '+':
                        stack.push(num);//“+”,压入原数字
                        break;
                    case '-':
                        stack.push(-num);//“-”,压入原数字的负数
                        break;
                    case '*':
                        stack.push(stack.pop() * num);//第一次出现这种情况时,字符串已经遍历到最后,flag为*
                        break;
                    case '/':
                        stack.push(stack.pop() / num);//第一次出现这种情况时,字符串已经遍历到第二个加号,flag仍然是“/”
                }
                flag = s.charAt(i);
                num = 0;
            }
        }
        int ans = 0;
        while(!stack.isEmpty()){
            ans = ans + stack.pop();
        }
        return ans;
    }
}

 

上一篇:Linux安装maven并设置阿里云镜像


下一篇:Implement strStr() - LeetCode