Evaluate Reverse Polish Notation

Evaluate 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


c++版本:
class Solution{
public:
    int evalRPN(vector<string> &tokens){
        if(tokens.size()==1)
            return stoi(*tokens.begin());
        stack<int> numbers;
        vector<string>::iterator it=tokens.begin();
        int op1=0;
        int op2=0;
        while(it!=tokens.end()){
                if(*it=="+"||*it=="-"||*it=="*"||*it=="/"){
                    op2=numbers.top();
                    numbers.pop();
                    op1=numbers.top();
                    numbers.pop();
                    if(*it=="+")  numbers.push(op1+op2);
                    else if(*it=="-") numbers.push(op1-op2);
                    else if(*it=="*") numbers.push(op1*op2);
                    else              numbers.push(op1/op2);
                }
                else
                    numbers.push(stoi(*it));
                    it++;
            }
                return numbers.top();}

};

  Java版本:

public class Solution {
    public int evalRPN(String[] tokens) {
        int returnValue = 0;
        String operators = "+-*/";
        Stack<String> stack = new Stack<String>();
        for(String t:tokens) {
            if(!operators.contains(t)) {
                stack.push(t);
            } else {
                int a = Integer.valueOf(stack.pop());
                int b = Integer.valueOf(stack.pop());
                int index = operators.indexOf(t);
                  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;
                  }
            }
        }
        returnValue = Integer.valueOf(stack.pop());
        return returnValue;
    }
}
原文地址:https://www.cnblogs.com/zlz-ling/p/4035497.html