题解 | 后缀表达式求值

后缀表达式求值

https://www.nowcoder.com/practice/22f9d7dd89374b6c8289e44237c70447

import java.util.*;


public class Solution {
    /**
     * 
     * @param tokens string字符串一维数组 
     * @return int整型
     */
    public int evalRPN (String[] tokens) {
        // write code here
        Stack<Integer> stack=new Stack();
        for(String token:tokens){
            if(isNumber(token)){
                stack.push(Integer.parseInt(token));
            }else{
                int a=stack.pop();
                int b=stack.pop();
                switch(token){
                    case "+": stack.push(a+b);break;
                    case "-": stack.push(a-b);break;
                    case "*": stack.push(a*b);break;
                    case "/": stack.push(a/b);break;
                    default: throw new IllegalArgumentException("未知参数");
                }
            }
        }

        return stack.pop();


    }

    public boolean isNumber(String param){
        try{
                Integer.parseInt(param);
        }catch(Exception e){
return false;
        }
        return true;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务