版权声明:本文为博主原创文章,未经博主允许不得转载。
难度:中等
要求:
求逆波兰表达式的值。
在逆波兰表达法中,其有效的运算符号包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。
样例
["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 == null || tokens.length == 0) {
return 0;
}
Stack<String> stack = new Stack();
int i = 0;
stack.add(tokens[i]);
i++;
int n1 = 0;
int n2 = 0;
while (!stack.isEmpty() && i < tokens.length) {
String s = tokens[i];
switch (s) {
case "+":
n1 = Integer.parseInt(stack.pop());
n2 = Integer.parseInt(stack.pop());
stack.add(String.valueOf(n1 + n2));
break;
case "-":
n1 = Integer.parseInt(stack.pop());
n2 = Integer.parseInt(stack.pop());
stack.add(String.valueOf(n2 - n1));
break;
case "*":
n1 = Integer.parseInt(stack.pop());
n2 = Integer.parseInt(stack.pop());
stack.add(String.valueOf(n1 * n2));
break;
case "/":
n1 = Integer.parseInt(stack.pop());
n2 = Integer.parseInt(stack.pop());
stack.add(String.valueOf(n2 / n1));
break;
default:
stack.add(s);
break;
}
i++;
}
String s = stack.pop();
return Integer.parseInt(s);
}
}