LeetCode Evaluate Reverse Polish Notation
题目:
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
解题关键在于Reverse Polish Notation.逆波兰表示法其特点是所有操作符置于操作数的后面,因此也被称为后缀表示法。逆波兰记法不需要括号来标识操作符的优先级。
在了解了逆波兰表示以后,决定使用Stack数据结构。在解题过程中利用2个栈。
第一栈存放数字,第二个栈存放的是符号。
其实每遇到一个符号,就可以把把数据栈中2个数字弹出相加,把结果压入栈中。
如果遇到一个符号。数据栈中的数据不足两个。将符号压入符号栈中。
最后符号栈为空时,将数据栈的栈顶返回就是结果了。
犯了个小错误,就是减法考虑到前后,一开始未考虑。
public class Solution {
public int evalRPN(String[] tokens) {
int result = 0;
int length = tokens.length;
if(length == 0)
{
return 0;
}
Stack<Integer> stack = new Stack<Integer>();
Stack<String> symbol = new Stack<String>();
for(int i=0;i<length;i++)
{
if(tokens[i].equals("+"))
{
if(stack.size()<2)
{
symbol.add(tokens[i]);
}
else
{
int m = (int)stack.pop();
int n = (int)stack.pop();
stack.push(m+n);
}
}
else if(tokens[i].equals("-"))
{
if(stack.size()<2)
{
symbol.add(tokens[i]);
}
else
{
int m = (int)stack.pop();
int n = (int)stack.pop();
stack.push(n-m);
}
}
else if(tokens[i].equals("*"))
{
if(stack.size()<2)
{
symbol.add(tokens[i]);
}
else
{
int m = (int)stack.pop();
int n = (int)stack.pop();
stack.push(m*n);
}
}
else if(tokens[i].equals("/"))
{
if(stack.size()<2)
{
symbol.add(tokens[i]);
}
else
{
int m = (int)stack.pop();
int n = (int)stack.pop();
stack.push(n/m);
}
}
else
{
stack.add(Integer.parseInt(tokens[i]));
}
}
while(!symbol.isEmpty())
{
String sym = symbol.pop();
if(sym.equals("+"))
{
int m = (int)stack.pop();
int n = (int)stack.pop();
stack.push(m+n);
}
else if(sym.equals("-"))
{
int m = (int)stack.pop();
int n = (int)stack.pop();
stack.push(n-m);
}
else if(sym.equals("*"))
{
int m = (int)stack.pop();
int n = (int)stack.pop();
stack.push(m*n);
}
else if(sym.equals("/"))
{
int m = (int)stack.pop();
int n = (int)stack.pop();
stack.push(n/m);
}
}
result = stack.pop();
return result;
}
}