LeetCode day one (2)

 Problem Description:

  

Polish calculate the inverse value (postfix expression) of
Contains only operator "+", "-", "*" and "/", the operand may be an integer or other expressions
E.g:
  ["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 

ideas:
  consider implemented using a stack structure, taken two stack elements directly performs arithmetic operation in the face of Fahao operation, then the result of the operation again pushed back the stack,
  the last remaining elements in the stack is targeted results.
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();
    }
}

 

Guess you like

Origin www.cnblogs.com/lc1475373861/p/12007106.html