150. 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
解法一
后缀表达式,采用栈来解决,如果是数字则入栈;如果是运算符,将栈顶的两位数出栈,结合运算符运算后入栈。
// @Author taotao
// @ComplexityTime O(n) @Space O(n)
// @method 采用stack解决,注意字符串相等用equals
public class Solution {
public int evalRPN(String[] tokens) {
if (tokens.length == 0 || tokens == null) { return 0; }
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < tokens.length; i++) {
String str = tokens[i];
if (!str.equals("+") && !str.equals("-") && !str.equals("*") && !str.equals("/")) {
stack.push(Integer.parseInt(tokens[i]));
} else {
int param0 = stack.pop(), param1 = stack.pop(), temp = 0;
switch (tokens[i]) {
case "+":
temp = param1 + param0;
break;
case "-":
temp = param1 - param0;
break;
case "*":
temp = param1 * param0;
break;
case "/":
temp = param1 / param0;
break;
}
stack.push(temp);
}
}
return stack.pop();
}
}
本文介绍了一种使用栈来解决逆波兰表达式求值问题的方法。通过遍历输入的字符串数组,当遇到数字时将其压入栈中,遇到运算符时从栈中弹出两个元素进行计算并将结果压回栈中。最终栈顶元素即为表达式的值。
308

被折叠的 条评论
为什么被折叠?



