算法通关村第四关|黄金挑战|表达式问题
1.计算器问题
给定一个内容为表达式的字符串,计算结果。
class Solution {public int calculate(String s) {Deque<Integer> stack = new ArrayDeque<Integer>();char preSign = '+';int num = 0;int n = s.length();for (int i = 0; i < n; i++) {if (Character.isDigit(s.charAt(i))) {num = num * 10 + s.charAt(i) - '0';}if (!Character.isDigit(s.charAt(i)) && s.charAt(i) != ' ' || i == n - 1) {switch (preSign) {case '+':stack.push(num);break;case '-':stack.push(-num);break;case '*':stack.push(stack.pop() * num);break;default:stack.push(stack.pop() / num);break;}preSign = s.charAt(i);num = 0;}}int ans = 0;while (!stack.isEmpty()) {ans += stack.pop();}return ans;}
}
2.逆波兰表达式(后缀表达式)
给定一个逆波兰表达式,计算结果。
上一题是中缀表达式,这一题是后缀表达式,所以基本思路还是相似的,只是中缀表达式需要将栈中的栈顶元素和还未入栈的元素进行计算,而后缀表达式遇到数字就压栈,遇到符号就拿出来栈顶的两个元素进行计算。
tips:中缀表达式更贴近我们平时用来计算,但是对于计算机来说是很复杂的。而前缀和后缀表达式对于计算机来说处理更快,所以需要将中缀表达式转换为前缀或者后缀表达式再求值。
public int evalRPN(String[] tokens) {Stack<Integer> stack = new Stack<>();for (String token : tokens) {if (!Character.isDigit(token.charAt(0)) && token.length() == 1) {int b = stack.pop();int a = stack.pop();switch (token) {case "+":stack.push(a + b);break;case "-":stack.push(a - b);break;case "*":stack.push(a * b);break;case "/":stack.push(a / b);break;}} else {stack.push(Integer.parseInt(token));}}return stack.pop();
}
如果对您有帮助,请点赞关注支持我,谢谢!❤
如有错误或者不足之处,敬请指正!❤
个人主页:星不易 ♥
算法通关村专栏:不易|算法通关村 ♥