写的挺工整的。但是有冗余部分,可以合并一下 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>
点赞

相关推荐

我是没经验的毕业生,这啥情况啊会不会是hr在刷kpi
JamesGosli...:字节boss属于是群发了,我都快入职字节了,其他部门还在和我boss打招呼
点赞 评论 收藏
分享
点赞 评论 收藏
分享
05-26 10:24
门头沟学院 Java
qq乃乃好喝到咩噗茶:其实是对的,线上面试容易被人当野怪刷了
找工作时遇到的神仙HR
点赞 评论 收藏
分享
牛客网
牛客网在线编程
牛客网题解
牛客企业服务