import java.util.*; import java.lang.Integer; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 返回表达式的值 * @param s string字符串 待计算的表达式 * @return int整型 */ public static int solve(String s) { // write code here //如果有括号 则借助栈先处理括号 没有括号直接运算 if (s.length() == 0) { return 0; } if (s.length() == 1) { return Integer.valueOf(s); } if (s.contains("(")) { Stack<String> stack = new Stack<>(); //所有字符均入栈 遇到右括号要停下来计算 for (int i = 0; i < s.length(); i++) { char next = s.charAt(i); if (next == ')') { //计算当前()中的值并把结果压到栈里 int value = calculate(stack); stack.push(value + ""); } else { stack.push(String.valueOf(next)); } } //循环完后 所有的括号都处理掉了 String temp = ""; while (!stack.isEmpty()) { temp = stack.pop() + temp; } if (temp.equals("")) { return 0; } else { return calculateWithStr(temp); } } else { return calculateWithStr(s); } } private static int calculate(Stack<String> stack) { StringBuilder sb = new StringBuilder(); while (!stack.peek().equals("(")) { sb.insert(0, stack.pop()); } //把左括号弹出来 stack.pop(); String curS = sb.toString(); //计算这个没有括号的串的值 int value = calculateWithStr(curS); return value; } private static int calculateWithStr(String str) { str = str.replace("+-", "-"); str = str.replace("--", "+"); str = str.replace("*-", "&"); String[] s1 = str.split("\\+"); int res = 0; for (int i = 0; i < s1.length; i++) { String next = s1[i]; if (next.contains("-")) { //处理减法逻辑 res += calculateSubtract(next); } else { if (next.contains("*") || next.contains("&")) { res += calculateX(next); } else { res += Integer.valueOf(next); } } } return res; } /** * 负号和减号是一样的要处理 * 这个方法里面只有 减法和乘法注意 -1 、-1*2的情况 */ private static int calculateSubtract(String str) { String[] s1 = str.split("-"); //处理 -1、-1*2这种情况-1*2 = 0-1*2 int res = 0; if (!s1[0].equals("")) { //第一个数可能是个单纯的数字 也可能是个乘法表达式 if (s1[0].contains("*") || s1[0].contains("&")) { res = calculateX(s1[0]); } else { res = Integer.valueOf(s1[0]); } } for (int i = 1; i < s1.length; i++) { String next = s1[i]; if (next.contains("*") || next.contains("&")) { res -= calculateX(next); } else { res -= Integer.valueOf(next); } } return res; } private static int calculateX(String s) { s = s.replace("&","*-"); String[] s2 = s.split("\\*"); int tempX = Integer.valueOf(s2[0]); for (int j = 1; j < s2.length; j++) { tempX = tempX * Integer.valueOf(s2[j]); } return tempX; } }