150. Evaluate Reverse Polish Notation

来源:互联网 发布:迅雷看看有mac版吗 编辑:程序博客网 时间:2024/06/07 15:40

Evaluate the value of anarithmetic 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

    翻译: 在逆向波兰记法中评估算术表达式的值。有效运算符为+ -*/每个操作数可以是整数或另一个表达式。

    题目就是栈那一节的表达式求值,但是它稍微简单一点。没有括号,不用考虑符号的优先级别。还有注意一点的就是,LeetCode的jdk是1.7以下,所以不支持switch表达式是字符串。代码如下:

public class Solution {

    public int evalRPN(String[] tokens) {

           String op="+-*/";

           Stack<String> stack=new Stack();

           for(String s: tokens){

                 if(op.contains(s)){

                      int a=Integer.valueOf(stack.pop());

                      int b=Integer.valueOf(stack.pop());

                      int index=op.indexOf(s);

                      switch(index){

                      case 0:

                            stack.push(String.valueOf(a+b));

                            break;

                      case 1:

                            stack.push(String.valueOf(b-a));

                            break;

                      case 2:

                            stack.push(String.valueOf(a*b));

                            break;

                      case 3:

                            stack.push(String.valueOf(b/a));

                            break;

                      }

                 }else{

                      stack.push(s);

                 }

    }

    return Integer.valueOf(stack.pop());

}

}

0 0
原创粉丝点击