Evaluate Reversed Polish Notation

来源:互联网 发布:梦里花落知多少百度云 编辑:程序博客网 时间:2024/04/29 19:28

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

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


wiki explanation for RPN:

http://en.wikipedia.org/wiki/Reverse_Polish_notation


Using Stack

public class Solution {    public int evalRPN(String[] tokens) {        //by stack        //pay attention to minus and divide        Stack<String> st = new Stack<String>();        int len = tokens.length;        int res = 0;        if(len == 0) return 0;        if(len == 1) return Integer.parseInt(tokens[0]);        for(int i=0; i<len; i++){           if(tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals ("*") || tokens[i].equals("/")){               int a = Integer.parseInt(st.pop());               int b = Integer.parseInt(st.pop());                              if(tokens[i].equals ("+")){                   st.push(String.valueOf(a+b));                                  }               else if (tokens[i].equals ("-")){                   st.push(String.valueOf(b-a));       // not a-b                                 }               else if(tokens[i].equals ("*")){                   st.push(String.valueOf(a*b));                                }               else if(tokens[i].equals("/")){                   st.push(String.valueOf(b/a));       // not a/b                                 }           }           else {               st.push(tokens[i]);           }                    }        res = Integer.parseInt(st.pop());        return res;    }}


After searching others' solution, find using switch case is a good choice

Eg: http://www.programcreek.com/2012/12/leetcode-evaluate-reverse-polish-notation/

0 0
原创粉丝点击