关注
写的挺工整的。但是有冗余部分,可以合并一下 import java.util.*; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); while (scan.hasNext()) { String s = scan.nextLine(); s = s.replace("[", "("); s = s.replace("{", "("); s = s.replace("]", ")"); s = s.replace("}", ")"); int res = solution(s); System.out.println(res); } } public static int solution(String s) { char ops = '+'; Stack<integer> stack = new Stack<>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == ' ') continue; if (c == '+' || c == '-' || c == '*' || c == '/') { ops = c; continue; } int num = 0; if (Character.isDigit(c)) { while (i < s.length() && Character.isDigit(s.charAt(i))) { num = num * 10 + s.charAt(i) - '0'; i++; } i--; } else if (c == '(') { int left = i; int right = i + 1; int count = 1; while (right < s.length() && count > 0) { if (s.charAt(right) == '(') count++; else if (s.charAt(right) == ')') count--; right++; } i = right - 1; num = solution(s.substring(left + 1, right - 1)); } if (ops == '+') stack.push(num); else if (ops == '-') stack.push(-num); else if (ops == '*') stack.push(stack.pop() * num); else if (ops == '/') stack.push(stack.pop() / num); } int res = 0; while (!stack.isEmpty()) res += stack.pop(); return res; } }</integer>
点赞
相关推荐

点赞 评论 收藏
分享
05-14 22:37
中国科学技术大学 Java 点赞 评论 收藏
分享
点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 我的求职总结 #
6806次浏览 142人参与
# 辞职之后最想做的一件事 #
7594次浏览 81人参与
# 我的实习日记 #
2410138次浏览 25234人参与
# 选offer应该考虑哪些因素 #
7188次浏览 109人参与
# 一人一个landing小技巧 #
33405次浏览 618人参与
# 工作后会跟朋友渐行渐远吗 #
20012次浏览 153人参与
# 你想留在一线还是回老家? #
35235次浏览 429人参与
# 你小时候最想从事什么职业 #
89486次浏览 1675人参与
# 设计人如何选offer #
107915次浏览 706人参与
# 生物制药/化工校招攻略 #
42546次浏览 282人参与
# 比亚迪求职进展汇总 #
702840次浏览 3058人参与
# 你们公司哪个部门最累? #
13779次浏览 114人参与
# 毕业季,给职场新人一些建议 #
5779次浏览 83人参与
# 大学最后一个寒假,我想…… #
35248次浏览 451人参与
# 毕业后不工作的日子里我在做什么 #
167162次浏览 1478人参与
# 秋招想进国企该如何准备 #
56528次浏览 363人参与
# 市场营销面经 #
40826次浏览 298人参与
# 25届网易互娱暑实进度 #
72031次浏览 672人参与
# 工作中的卑微时刻 #
8724次浏览 54人参与
# 薪资爆料 #
101520次浏览 1035人参与