题解 | #牛牛计算器#
牛牛计算器
https://www.nowcoder.com/practice/192ac31d5e054abcaa10b72d9b01cace
定义函数function做运算操作,处理'-'比较麻烦,我的做法是二元和一元身份分开,一元加入操作数栈计算时提取。
主函数中,分不同情况处理不同字符,注意循环计算到无可计算为止,尤其是面对右括号。
小坑null不能和字符比较。
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return int整型 */ void function (Deque<String> que1, Deque<Character> que2) { int a, b; if (que2.peekLast() != null) { char c = que2.pollLast(); switch (c) { case '+': b = Integer.parseInt(que1.pollLast()); if (que1.peekLast() == "-") { b = -b; que1.pollLast(); } a = Integer.parseInt(que1.pollLast()); if (que1.peekLast() == "-") { a = -a; que1.pollLast(); } que1.addLast(String.valueOf(a + b)); break; case '-': b = Integer.parseInt(que1.pollLast()); if (que1.peekLast() == "-") { b = -b; que1.pollLast(); } a = Integer.parseInt(que1.pollLast()); if (que1.peekLast() == "-") { a = -a; que1.pollLast(); } que1.addLast(String.valueOf(a - b)); break; case '*': b = Integer.parseInt(que1.pollLast()); if (que1.peekLast() == "-") { b = -b; que1.pollLast(); } a = Integer.parseInt(que1.pollLast()); if (que1.peekLast() == "-") { a = -a; que1.pollLast(); } que1.addLast(String.valueOf(a * b)); break; } } } public int calculate (String s) { Deque<String> que1 = new ArrayDeque<>(); Deque<Character> que2 = new ArrayDeque<>(); s = s.replace(" ", ""); char[] ch = s.toCharArray(); int a, b; for (int i = 0; i < ch.length; ++i) { switch (ch[i]) { case '(': que2.addLast('('); break; case '+': while (!que2.isEmpty() && (que2.peekLast() == '+' || que2.peekLast() == '-' || que2.peekLast() == '*')) function(que1, que2); que2.addLast('+'); break; case '-': if (i == 0 || (ch[i + 1] == '(' && !(ch[i - 1] <= '9' && ch[i - 1] >= '0'))|| i > 0 && !(ch[i - 1] <= '9' && ch[i - 1] >= '0') && ch[i - 1] != ')') { que1.add("-"); break; } if (!que2.isEmpty() && que2.peekLast() != '(') { while (!que2.isEmpty() && (que2.peekLast() == '+' || que2.peekLast() == '-' || que2.peekLast() == '*')) function(que1, que2); } que2.addLast('-'); break; case '*': while (!que2.isEmpty() && que2.peekLast() == '*') { function(que1, que2); } que2.addLast('*'); break; case ')': while (!que2.isEmpty() && que2.peekLast() != '(') function(que1, que2); que2.pollLast(); break; default: int last = i + 1; while (last < ch.length && ch[last] >= '0' && ch[last] <= '9') last++; String ss = String.valueOf(ch, i, last - i); que1.addLast(ss); i = last - 1; } } while (!que2.isEmpty()) function(que1, que2); return Integer.parseInt(que1.pollLast()); } }