牛客编程巅峰赛S2第5场:牛牛与后缀表达式

题目描述:

原题链接
在这里插入图片描述
在这里插入图片描述

解题思路:

利用栈去模拟后缀表达式

参考代码:

    public long solve (String str) {
    
    
        // write code here
        Stack<Long> s = new Stack<>();
        long temp = 0;
        for(int i =0; i<str.length(); i++){
    
    
            if(str.charAt(i)>='0' && str.charAt(i)<='9'){
    
    
                temp*=10;
                temp+=str.charAt(i)-'0';
            }else if(str.charAt(i)=='#'){
    
    
                s.push(temp);
                temp = 0;
            }else{
    
    
                long p1 = s.pop();
                long p2 = s.pop();
                switch (str.charAt(i)){
    
    
                    case '+': s.push(p1+p2);break;
                    case '-': s.push(p2-p1);break;
                    case '*': s.push(p1*p2);break;
                }
            }
        }
        return s.peek();
    }

猜你喜欢

转载自blog.csdn.net/qq_44900959/article/details/110497481