一、原题
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
二、分析
这里的分析就援引百度文库对于逆波兰表达式的计算方法。
三、代码(JAVA)
import java.util.Stack; public class ReversePolishNotation { Stack<String> stack =new Stack(); public int evalRPN(String[] tokens) { if(tokens.length==0) return 0; int temp1,temp2,temp3; temp1=temp2=temp3=0; for(int i=0;i<tokens.length;i++){ if(tokens[i].equals("+")|| tokens[i].equals("-")|| tokens[i].equals("*")|| tokens[i].equals("/")){ if(tokens.length==1) return 0; temp1=Integer.parseInt(stack.peek()); stack.pop(); temp2=Integer.parseInt(stack.peek()); stack.pop(); if(tokens[i].equals("+")){ temp3=temp1+temp2; stack.push(Integer.toString(temp3));//计算结果同样要入栈 } else if(tokens[i].equals("*")){ temp3=temp1*temp2; stack.push(Integer.toString(temp3)); } else if(tokens[i].equals("/")){ temp3=temp2/temp1; // 注意temp2与temp1的顺序 stack.push(Integer.toString(temp3)); } else if(tokens[i].equals("-")){ temp3=temp2-temp1; stack.push(Integer.toString(temp3)); } } else{ temp3=Integer.parseInt(tokens[i]);//这里针对输入类似{“18”},既(s.length==1)&&(s[0]代表数字) stack.push(tokens[i]); } } return temp3; } }
【Leetcode】Evaluate Reverse Polish Notation答案
原文地址:http://blog.csdn.net/dr_titi/article/details/41594129