LeetCode每日一道(2)

 问题描述:

  

计算逆波兰式(后缀表达式)的值
运算符仅包含"+","-","*"和"/",被操作数可能是整数或其他表达式
例如:
  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9↵  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
Evaluate the value of an arithmetic expression in  Reverse Polish Notation.

Valid operators are+,-,*,/. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9↵  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

思路:
  考虑使用栈结构实现,在遇到运算法号的时候直接取出栈顶的两个元素进行运算操作,然后把运算结果重新压回栈,
  最后栈剩下的中元素为目标结果。
import java.util.Stack;
public class Solution {
    public int evalRPN(String[] tokens) {
        if(tokens==null){
            return 0;
        }
        Stack<Integer> stack = new Stack<Integer>();
        for(int i = 0;i < tokens.length; i++){
                if(tokens[i].equals("+")){
                    int a = Integer.valueOf(stack.pop());
                    int b = Integer.valueOf(stack.pop());
                    stack.push(a+b);
                }else if(tokens[i].equals("-")){
                    int a = Integer.valueOf(stack.pop());
                    int b = Integer.valueOf(stack.pop());
                    stack.push(b-a);
                }else if(tokens[i].equals("*")){
                    int a = Integer.valueOf(stack.pop());
                    int b = Integer.valueOf(stack.pop());
                    stack.push(a*b);
                }else if(tokens[i].equals("/")){ 
                    int a = Integer.valueOf(stack.pop());
                    int b = Integer.valueOf(stack.pop());
                    stack.push(b/a);
                }else{
                    stack.push(Integer.valueOf(tokens[i]));
                }
        }
        return stack.pop();
    }
}

猜你喜欢

转载自www.cnblogs.com/lc1475373861/p/12007106.html