题目描述:
根据 逆波兰表示法,求表达式的值。
有效的算符包括 +、-、*、/ 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
注意 两个整数之间的除法只保留整数部分。
可以保证给定的逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
来源:力扣(LeetCode)
思路:
逆波兰表达式:是非常经典的使用栈数据结构实现的内容;是计算机是思考方式!
我们常用的是中缀表达式,但是计算机喜欢的是后缀表达式,也就是逆波兰表达式!
就是将数字入栈,遇到符号,就将栈中元素弹出两个;后出栈的在前,先出栈的在后,进行计算;计算结果继续入栈成为栈顶元素!
代码:
class Solution {
public int evalRPN(String[] tokens) {
//逆波兰表达式,应该是 栈 中最经典的应用!
//遇到数字先入栈,遇到符号就 弹出两个数字进行计算处理!
//先弹出的数字再 计算符的后面,先弹出的再计算符的前面
Stack<Integer> stack = new Stack<>();
//String怎么转换成数字
for(int i = 0;i < tokens.length;i++){
if("+".equals(tokens[i])){
int b = stack.pop();
int a = stack.pop();
stack.push(a + b);
}else if("-".equals(tokens[i])){
int b = stack.pop();
int a = stack.pop();
stack.push(a - b);
}else if("*".equals(tokens[i])){
int b = stack.pop();
int a = stack.pop();
stack.push(a * b);
}else if("/".equals(tokens[i])){
int b = stack.pop();
int a = stack.pop();
stack.push(a / b);
}
else stack.push(Integer.parseInt(tokens[i]));
}
return (int)stack.pop();
}
}
优化代码:
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < tokens.length; i++) {
if ("+".equals(tokens[i])) {
stack.push(stack.pop() + stack.pop());
} else if ("-".equals(tokens[i])) {
stack.push(-stack.pop() + stack.pop());
} else if ("*".equals(tokens[i])) {
stack.push(stack.pop() * stack.pop());
} else if ("/".equals(tokens[i])) {
int temp1 = stack.pop();
int temp2 = stack.pop();
stack.push(temp2 / temp1);
} else {
stack.push(Integer.valueOf(tokens[i]));
}
}
return stack.pop();
}
}