题解 | #四则运算#

四则运算

https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
	    // 处理空格和多样括号 
        str = str.replaceAll("\\s","").replaceAll("\\[","(").replaceAll("\\]",")").replaceAll("\\{","(").replaceAll("\\}",")");
        char[] c = str.toCharArray();

        Stack<Integer> s1 = new Stack<>();
        Stack<Character> s2 = new Stack<>();
        StringBuilder number = new StringBuilder();

        Map<Character,Integer> priority = new HashMap<>();
        priority.put('+',1);
        priority.put('-',1);
        priority.put('*',2);
        priority.put('/',2);
        priority.put('(',0);

        for(int i=0;i<c.length;i++){
            char cc = c[i];
		    // ‘-’出现在第一个或者前面是运算符+'('时 负数
            if(cc=='-' && (i==0 || isSymbol(c[i-1]))){
                number.append(cc);
            }else if(Character.isDigit(cc)){
                number.append(cc);
			    // 最后一个或者下一个不是数字时,多位数结束存入栈1中
                if(i==c.length-1 || !Character.isDigit(c[i+1])){
                    s1.push(Integer.parseInt(number.toString()));
                    number.setLength(0);
                }
            }else if(cc=='('){
                s2.push(cc);
            }else if(cc==')'){
                while(s2.peek()!='('){
                    fun(s1,s2);
                }
                s2.pop();
            }else{
			    // 当前字符的优先级<=栈顶元素的优先级时 先计算前面的再放入栈
                while(!s2.isEmpty() && priority.get(cc) <= priority.get(s2.peek())){
                    fun(s1,s2);
                }
                s2.push(cc);
            }
        }

        while(!s2.isEmpty()){
            fun(s1,s2);
        }

        System.out.println(s1.peek());
    }

    public static boolean isSymbol(char c){
        if(c=='+' || c=='-' || c=='*' || c=='/' || c=='(') return true;
        else return false;
    }

    public static void fun(Stack<Integer> s1, Stack<Character> s2){
        char c = s2.pop();
        int b = s1.pop();
        int a = s1.pop();
        switch(c){
            case'+':
                s1.push(a+b);
                break;
            case'-':
                s1.push(a-b);
                break;
            case'*':
                s1.push(a*b);
                break;
            case'/':
                s1.push(a/b);
                break;
        }
    }
}

全部评论

相关推荐

勤奋努力的椰子这就开摆:美团骑手在美团工作没毛病
投递美团等公司10个岗位
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务