题目描述
根据逆波兰表示法,求表达式的值。
其实就是将中缀表达式转换成后缀表达式求值的过程。
说明:
- 整数除法只保留整数部分。
- 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
示例 1:
输入: ["2", "1", "+", "3", "*"]
输出: 9
解释: ((2 + 1) * 3) = 9
示例 2:
输入: ["4", "13", "5", "/", "+"]
输出: 6
解释: (4 + (13 / 5)) = 6
题目解析
用数据结构栈
来解决这个问题。
- 从前往后遍历数组
- 遇到数字则压入栈中
- 遇到符号,则把栈顶的两个数字拿出来运算,把结果再压入栈中
- 遍历完整个数组,栈顶数字即为最终答案
代码实现
public static String[] a = {"2","3","5","*","+","2","-","4","2","/","+"};
public static String soluation(){
Stack<String> stack = new Stack();
int length = a.length;
int num = 0;
for (int i = 0; i < length; i++) {
switch (a[i]) {
case "+":
if (stack.isEmpty() || stack.size() < 2) {
throw new RuntimeException("the expression is error");
}
num = StringToInt(stack.pop());
stack.push(intToString(StringToInt(stack.pop()) + num));
break;
case "-":
if (stack.isEmpty() || stack.size() < 2) {
throw new RuntimeException("the expression is error");
}
num = StringToInt(stack.pop());
stack.push(intToString(StringToInt(stack.pop()) - num));
break;
case "*":
if (stack.isEmpty() || stack.size() < 2) {
throw new RuntimeException("the expression is error");
}
num = StringToInt(stack.pop());
stack.push(intToString(StringToInt(stack.pop()) * num));
break;
case "/":
if (stack.isEmpty() || stack.size() < 2) {
throw new RuntimeException("the expression is error");
}
num = StringToInt(stack.pop());
stack.push(intToString(StringToInt(stack.pop()) / num));
break;
default:
stack.push(a[i]);
break;
}
}
return stack.pop();
}
复杂度计算
空间需要一个辅助的栈结构,大小不会超过n,所以空间复杂度为O(n)。
时间复杂度只需要遍历完整个表达式就可以结束,所以时间复杂度为O(n)。