逆波兰表达式求值
题目
求逆波兰表达式的值。
在逆波兰表达法中,其有效的运算符号包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。说明
什么是逆波兰表达式?
http://en.wikipedia.org/wiki/Reverse_Polish_notation样例
[“2”, “1”, “+”, “3”, ““] -> ((2 + 1) 3) -> 9
[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6题解
就是基本的栈的使用,需要注意的是处理好运算对象也是表达式的情况。
public class Solution {
/**
* @param tokens The Reverse Polish Notation
* @return the value
*/
public int evalRPN(String[] tokens) {
if (tokens.length == 1)
{
return Integer.valueOf(tokens[0]);
}
Stack<Integer> stack = new Stack<>();
for (int i=0;i<tokens.length;i++)
{
if (tokens[i].equals("+"))
{
int a = stack.pop();
int b = stack.pop();
stack.push(a+b);
}
else if (tokens[i].equals("-"))
{
int a = stack.pop();
int b = stack.pop();
stack.push(b-a);
}
else if (tokens[i].equals("*"))
{
int a = stack.pop();
int b = stack.pop();
stack.push(a*b);
}
else if (tokens[i].equals("/"))
{
int a = stack.pop();
int b = stack.pop();
stack.push(b/a);
}
else
{
String temp = tokens[i].substring(1,tokens[i].length());
if (temp.contains("+") || temp.contains("-") ||
temp.contains("*") || temp.contains("/"))
{
String[] newTokens = new String[tokens[i].length()];
for(int k=0;k<tokens[i].length();k++)
{
newTokens[k] = tokens[i].substring(k,k+1);
}
stack.push(evalRPN(newTokens));
}
else
{
stack.push(Integer.valueOf(tokens[i]));
}
}
}
return stack.pop();
}
}
Last Update 2016.11.17