解题思路:

使用栈
如果是数字入栈,如果是操作符取出栈中的top两个数字进行操作再将结果入栈


提交代码:

class Solution {
    public int evalRPN(String[] tokens) {
        if(tokens.length==0)	return 0;
        
        Stack<Integer> stack=new Stack<>();
        for(String s: tokens) {
        	if(s.equals("+")) {
        		stack.push(stack.pop()+stack.pop());
        	}else if(s.equals("-")) {
        		stack.push(-1*stack.pop()+stack.pop());
        	}else if(s.equals("*")) {
        		stack.push(stack.pop()*stack.pop());
        	}else if(s.equals("/")) {
        		int num1=stack.pop();
        		int num2=stack.pop();
        		stack.push(num2/num1);
        	}
        	else stack.push(Integer.parseInt(s));
        }
        
        return stack.pop();
    }
}

运行结果:
【leetcode】150.(Medium)Evaluate Reverse Polish Notation

相关文章:

  • 2021-07-19
  • 2022-02-03
  • 2022-12-23
  • 2022-12-23
  • 2021-09-08
  • 2021-09-02
  • 2021-09-13
  • 2021-10-09
猜你喜欢
  • 2021-09-27
  • 2021-06-24
  • 2021-07-29
  • 2022-02-27
  • 2021-06-04
  • 2021-10-25
  • 2022-01-22
相关资源
相似解决方案