Evaluate Reverse Polish Notation

Evaluate Reverse Polish Notation

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





这道题还是比较Easy,直接用堆栈,遇到数字就进栈,遇到运算符弹出两个数,将运算结果入栈。最后返回栈底元素就okay了
public class Solution {
    public int evalRPN(String[] tokens) {
        int top = -1;//栈指针
        int stack[] = new int[tokens.length / 2 + 1];
        
        for(int i = 0; i < tokens.length; i++){
            char temp = tokens[i].charAt(0);
            if(temp != '+' && !(tokens[i].length() == 1 && temp == '-')
                    && temp != '*' && temp != '/'){//数字直接入栈
                stack[++top] = Integer.valueOf(tokens[i]);
            }
            else{//元素符,弹两个数字出来计算
                int num1;
                int num2;
                int result = 0;
                
                num2 = stack[top--];
                num1 = stack[top--];
                switch(temp){
                    case '+':
                        result = num1 + num2;
                        break;//入栈
                    case '-':
                        result = num1 - num2;
                        break;
                    case '*':
                        result = num1 * num2;
                        break;
                    case '/':
                        result = num1 / num2;
                        break;
                }
                stack[++top] = result;//结果入栈
                
            }
        }
        return stack[top];
    }
}

 

 

posted on 2014-11-20 19:05  luckygxf  阅读(135)  评论(0编辑  收藏  举报

导航