保证字符串中的有效字符包括[‘0’-‘9’],‘+’,‘-’, ‘*’,‘/’ ,‘(’, ‘)’,‘[’, ‘]’,‘{’ ,‘}’。且表达式一定合法。
数据范围:表达式计算结果和过程中满足 ,字符串长度满足
数据范围:表达式计算结果和过程中满足 ,字符串长度满足
输入一个算术表达式
得到计算结果
3+2*{1+2*[-4/(8-6)+7]}
25
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); System.out.println(calculate(str)); } public static int calculate(String str) { // 处理特殊括号,注意替换后的值,不要写错了。且replace后要重新赋值给str str = str.replaceAll("\\[", "(").replaceAll("\\{", "(").replaceAll("]", ")").replaceAll("}", ")").replaceAll(" ", ""); //初始化两个栈,分别存放运算术和运算符 Stack<Integer> nums = new Stack<>(); Stack<Character> opts = new Stack<>(); char[] cs = str.toCharArray(); int n = cs.length; boolean flagOpts = false; boolean isNegativeNumber = false; for (int i = 0; i < n; i++) { char c = cs[i]; //判断负数、左括号、右括号、普通运算数、+-*/ if (Character.isDigit(c)) { int v = c - '0'; int j = i + 1; while (j < n && Character.isDigit(cs[j])) { v = v * 10 + cs[j++] - '0'; } i = j - 1; if (isNegativeNumber) { v = -v; isNegativeNumber = false; } nums.add(v); flagOpts = false ; } else { if (flagOpts && c == '-') { isNegativeNumber = true; continue; } if (c == '(') { opts.add(c); } else if (c == ')') { while (opts.peek() != '(') { cal(nums, opts); } opts.pop(); continue; } else { while (!opts.isEmpty() && getPrecedence(c) <= getPrecedence(opts.peek())) { cal(nums, opts); } opts.add(c); } flagOpts = true ; } } while (!opts.isEmpty()) { cal(nums, opts); } return nums.peek(); } // 获取运算符的优先级 public static int getPrecedence(char operator) { switch (operator) { case '+': case '-': return 1; case '*': case '/': return 2; } return 0; } public static void cal(Stack<Integer> nums, Stack<Character> opts) { if (nums.isEmpty() || nums.size() < 2) { return; } if (opts.isEmpty()) { return; } int b = nums.pop(), a = nums.pop(); char op = opts.pop(); int ans = 0; switch (op) { case '+' : ans = a + b; break; case '-': ans = a - b; break; case '*': ans = a * b; break; case '/': ans = a / b; break; default: break; } nums.add(ans); } }
// 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static String[] types = new String[]{"\\+","-","\\*", "/"}; public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.nextLine(); // 统一括号 s = s.replaceAll("\\[", "(").replaceAll("\\]", ")") .replaceAll("\\{", "(").replaceAll("\\}", ")"); // 开头减号一定是负号,先替换,防止用减号分割出现错误,最后计算时换回负号 s = s.replaceAll("\\(-", "(="); if (s.startsWith("-")) s = "="+s.substring(1); while (s.contains(")")) { //先计算括号内数据 int r = s.indexOf(")"); // 第一个右括号 //截止到第一个有括号的最后一个左括号为单一公式 int l = s.substring(0,r).lastIndexOf("("); // 计算不包含括号的单一公式 int ans = calc(s.substring(l+1, r), 0); // 结果写回算式,注意结果为负值的负号处理 s = s.substring(0, l) + (ans+"").replace("-", "=") + s.substring(r+1); } System.out.print(calc(s, 0)); } public static int calc(String s, int t) { // 按加减乘除四次分割,可以确保先乘除后加减 int ans = 0; //加法的初始值 if (t == 2) ans = 1; //乘法的初始值 // 防止前面括号带入 s = s.replace("(", "").replace(")", ""); // 按顺序分割 String[] plus = s.split(types[t]); for (int i=0; i<plus.length; i++) { String p = plus[i]; if (t == 0) ans += calc(p, t+1); else if (t == 1) { int curr = calc(p, t+1); // 减法需要先得到第一个,后面逐次减法 if (i == 0) ans = curr; else ans -= curr; } else if (t == 2) { ans *= calc(p, t+1); } else if (t == 3) { int curr = Integer.parseInt(p.replaceAll("=", "-")); // 除法需要先得到第一个,后面逐次除法 if (i == 0) ans = curr; else ans /= curr; } } return ans; } }
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { // 存放算数优先级 public static HashMap<Character, Integer> map = new HashMap<Character, Integer>() { //这里泛型必须写 // 声明优先级 { put('-', 1); put('+', 1); put('*', 2); put('/', 2); } }; public static boolean isNumber(char c) { return Character.isDigit(c); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); System.out.println(calculate(str)); } public static int calculate(String str) { // 处理特殊括号,注意替换后的值,不要写错了。且replace后要重新赋值给str str = str.replaceAll("\\[", "(").replaceAll("\\{", "(").replaceAll("\\]", ")").replaceAll("\\}", ")").replaceAll(" ", ""); // 处理负数 for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '-') { if (i == 0 || str.charAt(i - 1) == '+' || str.charAt(i - 1) == '-' || str.charAt(i - 1) == '*' || str.charAt(i - 1) == '/' || str.charAt(i - 1) == '(') str = str.substring(0, i) + "#" + str.substring(i + 1); } } //初始化两个栈,分别存放运算术和运算符 Stack<Integer> nums = new Stack<>(); Stack<Character> opts = new Stack<>(); char[] cs = str.toCharArray(); int n = cs.length; for (int i = 0; i < n; i++) { char c = cs[i]; //判断负数、左括号、右括号、普通运算数、+-*/ if (c == '#') { int j = i + 1, v = 0; // 运算符往后一位,所以是i+1,正数会直接是j=i while (j < n && isNumber(cs[j])) { v = v * 10 + cs[j++] - '0'; } nums.add(-v); i = j - 1; //多位数处理 } else if (c == '(') { opts.add(c); } else if (c == ')') { // 计算括号内的数据,直到栈顶为(为止 while (opts.peek() != '(') { cal(nums, opts); } opts.pop(); //左括号出栈 } else { // 正数 if (isNumber(c)) { int j = i, v = 0; while (j < n && isNumber(cs[j])) { v = v * 10 + cs[j++] - '0'; } nums.add(v); i = j - 1; } else { while(!opts.isEmpty() && opts.peek() != '('){ char prev = opts.peek(); if(map.get(prev) >= map.get(c)){ cal(nums,opts); }else{ break; } } opts.add(c); } } } while (!opts.isEmpty()) { cal(nums, opts); } return nums.peek(); } public static void cal(Stack<Integer> nums, Stack<Character> opts) { if (nums.isEmpty() || nums.size() < 2) { return; } if (opts.isEmpty()) { return; } int b = nums.pop(), a = nums.pop(); char op = opts.pop(); int ans = 0; switch (op) { case '+' : ans = a + b; break; case '-': ans = a - b; break; case '*': ans = a * b; break; case '/': ans = a / b; break; default: break; } nums.add(ans); } }
import java.util.Scanner; import java.util.*; import java.util.stream.Collectors; import java.text.DecimalFormat; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { private static Map<Character, Integer> ***bsp;= new HashMap<>(); public static void main(String[] args) { por.put('+', 0); por.put('-', 0); por.put('*', 1); por.put('/', 1); Scanner sc = new Scanner(System.in); while (sc.hasNextLine()) { String str = sc.nextLine().trim().replace("{", "(").replace("}", ")") .replace("[", "(").replace("]", ")"); if (str.startsWith("-")) { str = "0" + str; } StringBuilder sb0 = new StringBuilder(); for (int i = 0; i < str.length(); i++) { if (i > 0 && str.charAt(i) == '-' && str.charAt(i - 1) == '(') { sb0.append("0"); } sb0.append(str.charAt(i)); } str = sb0.toString(); // System.out.println(str); Stack<Character> stack = new Stack<>(); List<String> list = new ArrayList<>(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); switch (c) { case '+': case '-': case '*': case '/': while (stack.size() > 0 && stack.peek() != '(' && por.get(c) <= por.get(stack.peek())) { list.add(stack.pop() + ""); } stack.push(c); break; case '(': stack.push(c); break; case ')': while (stack.size() > 0) { Character pop = stack.pop(); if (pop != '(') { list.add(pop + ""); } else { break; } } break; default: String num = c + ""; while (i < str.length() - 1 && str.charAt(i + 1) >= '0' && str.charAt(i + 1) <= '9') { num += str.charAt(i + 1); i++; } list.add(num); } } while (stack.size() > 0) { list.add(stack.pop() + ""); } double res = calc(list.toArray(new String[]{})); DecimalFormat df = new DecimalFormat("0.################"); System.out.println(df.format(res)); } } private static double calc(String[] pattern) { for (int i = pattern.length - 1; i >= 0; i--) { String s = pattern[i]; if (s.length() == 1 && por.containsKey(s.charAt(0)) && i > 1 && isNum(pattern[i - 1]) && isNum(pattern[i - 2])) { double v1 = Double.parseDouble(pattern[i - 1]); double v2 = Double.parseDouble(pattern[i - 2]); double res = getRes(s, v1, v2); pattern[i] = "null"; pattern[i - 2] = res + ""; pattern[i - 1] = "null"; } } String[] arr = Arrays.stream(pattern).filter(s -> !s.equals("null")).collect(Collectors.toList()).toArray(new String[]{}); if(arr.length==1){ return Double.parseDouble(arr[0]); } if (arr.length == 3) { double r = getRes(arr[arr.length - 1], Double.parseDouble(arr[1]), Double.parseDouble(arr[0])); return r; } return calc(arr); } private static double getRes(String op, double v1, double v2) { double res; switch (op) { case "+": res = v2 + v1; break; case "-": res = v2 - v1; break; case "*": res = v2 * v1; break; default: res = v2 / v1; break; } return res; } private static boolean isNum(String value) { try { Double.parseDouble(value); } catch (NumberFormatException e) { return false; } return true; } }
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.nextLine(); //问题3:括号问题,计算的先后顺序 s = s.replace("{", "("); s = s.replace("[", "("); s = s.replace("}", ")"); s = s.replace("]", ")"); //1+(8*2-1+3) StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); //问题1:第一个数字与(数字,数字为负数的处理 将负数拼接 eg:-3+2*{1+2*[-4/(8-6)+7]} (0-3)+2*(1+2*((0-4)/(8-6)+7)) if (c == '-' && (i == 0 || (i > 1 && s.charAt(i - 1) == '('))) { stringBuilder.append("(0" + s.charAt(i) + "" + s.charAt(i + 1) + ")"); i += 1; } else { stringBuilder.append(c); } } int result = handled(stringBuilder.toString()); System.out.println(result); } private static int handled(String s) { Stack<Integer> numStack = new Stack<>();//数字栈 Stack<Character> characterStack = new Stack<>();//字符栈 int count = 0;//记录当前字符是否是大于10的数字 for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (Character.isDigit(c)) { if (!numStack.isEmpty()&&count + 1 == i) { Integer pop = numStack.pop(); numStack.push(Integer.valueOf(pop + "" + c)); } else { count = i; numStack.push(Integer.valueOf(c + "")); } } else if (c == '(') { characterStack.push(c); } else if (c == ')') { while (!characterStack.isEmpty() && characterStack.peek() != '(') { calcute(characterStack, numStack); } characterStack.pop();//弹出'(' } else if (c == '+' || c == '-' || c == '*' || c == '/') { //问题2:四则运算顺序,先乘除后加减 //问题4:使用栈存储数字时计算应从左向右 否则会出现:3*5+8-0*3-6+0+0 15+8-0-6+0+0=29情况 while (!characterStack.isEmpty() && getPrecedence(characterStack.peek()) >= getPrecedence(c)) { calcute(characterStack, numStack); } characterStack.push(c); } } //计算剩余非括号内的算式 while (!characterStack.isEmpty()) { calcute(characterStack, numStack); } return numStack.pop(); // 返回最终计算结果 } // 获取运算符的优先级 public static int getPrecedence(char operator) { switch (operator) { case ')': return 0; case '+': case '-': return 1; case '*': case '/': return 2; } return 0; } //进行计算 public static void calcute(Stack<Character> characterStack, Stack<Integer> numStack) { Integer a = numStack.pop();//先进后出,注意顺序 Integer b = numStack.pop(); Character operate = characterStack.pop(); int result = 0; switch (operate) { case '-': result = b - a; break; case '+': result = b + a; break; case '*': result = b * a; break; case '/': result = b / a; break; } numStack.push(result); } }
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { /** * 简单运算,只包含 加 减 乘 除 * */ public int sampleCal(String inputStr) { //负责处理只包含+-*/表达式局部运算 Stack calStack = new Stack(); //负责表达式中括号的完整性 //Stack bracketStack = new Stack(); int cur_char_type = -1;//当前字符类型 -1:未知 0:数字 1:字母 int last_cal_type = -1;//上一个计算符号-1:未知 0: +或- 1: *或/ int next_cal_type = -1;//下一个计算符号-1:未知 0: +或- 1: *或/ StringBuilder digitSb = new StringBuilder(); for(int i = 0; i < inputStr.length(); i ++) { char curChr = inputStr.charAt(i); if(isDigit(curChr)) { //当前字符是数字 cur_char_type = 0; digitSb.append(curChr); if(i + 1 < inputStr.length() && isDigit(inputStr.charAt(i + 1))) { //下一个字符也是数字 continue; } else if(i + 1 >= inputStr.length()) { //当前字符已经是最后一个字符 calStack.push(String.valueOf(digitSb)); digitSb = new StringBuilder(); if(!calStack.isEmpt() && calStack.getStackSize() == 3) { //如果不为空,则出栈并计算 String curCal = ""; curCal = calStack.pop() + curCal; curCal = calStack.pop() + curCal; curCal = calStack.pop() + curCal; int calResult = calAB(curCal); //System.out.println(calResult); return calResult; } else if(!calStack.isEmpt() && calStack.getStackSize() > 3) { while(!calStack.isEmpt()) { String curCal = ""; curCal = calStack.pop() + curCal; curCal = calStack.pop() + curCal; curCal = calStack.pop() + curCal; int calResult = calAB(curCal); if(calStack.isEmpt()) { //System.out.println(calResult); return calResult; } else { calStack.push(String.valueOf(calResult)); } } } } else { //下一个字符不是数字,说明本次数字只有1个,已经取完 //TODO String digit = digitSb.toString(); digitSb = new StringBuilder(); if(isMutiDiv(inputStr.charAt(i + 1))) { //如果下一个符号是 *或/ if(last_cal_type == 1) { //当前数字前面的符号是 * 或 / //那么先入栈,再出栈3次把表达式取出,计算出表达式 calStack.push(digit); String curCal = ""; curCal = calStack.pop() + curCal; curCal = calStack.pop() + curCal; curCal = calStack.pop() + curCal; int calResult = calAB(curCal); calStack.push(String.valueOf(calResult)); } else if(last_cal_type == 0) { //当前数字前面的符号是 + 或 - calStack.push(digit); } else if(last_cal_type == -1) { //上一个符号未知,直接push calStack.push(digit); } } else if(isAddSub(inputStr.charAt(i + 1))) { if(last_cal_type == -1) { //上一个符号未知,直接push calStack.push(digit); } else { //如果下一个符号是 + 或 - //那么先入栈,再出栈3次把表达式取出,计算出表达式 //然后再入栈 calStack.push(digit); String curCal = "";; curCal = calStack.pop() + curCal; curCal = calStack.pop() + curCal; curCal = calStack.pop() + curCal; int calResult = calAB(curCal); calStack.push(String.valueOf(calResult)); } } } } else if(isAddSub(curChr)) { if(!calStack.isEmpt() && calStack.getStackSize() == 3) { //如果不为空,则出栈并计算 String curCal = ""; curCal = calStack.pop() + curCal; curCal = calStack.pop() + curCal; curCal = calStack.pop() + curCal; int calResult = calAB(curCal); calStack.push(String.valueOf(calResult)); } last_cal_type = 0; if(i == 0 && curChr == '-') { //如果第一个字符前面带有-号,默认在前面加上0 calStack.push("0"); } calStack.push(String.valueOf(curChr)); } else if(isMutiDiv(curChr)) { last_cal_type = 1; calStack.push(String.valueOf(curChr)); } } return -1; } public void solution(String inputStr) { //负责表达式中括号的完整性 Stack bracketStack = new Stack(); if(!isContansBracket(inputStr)) { //没带括号 int result = sampleCal(inputStr); System.out.println(result); } else { //带有扩号 for(int i = 0; i < inputStr.length(); i ++) { char curChr = inputStr.charAt(i); bracketStack.push(String.valueOf(curChr)); if(isLittleBracketEnd(curChr)) { //小括号结束符号 String sampleCalStr = ""; String popStr = ""; bracketStack.pop(); // ( do { sampleCalStr = popStr + sampleCalStr; popStr = bracketStack.pop(); } while (!isLittleBracketStart(popStr.charAt(0))); //System.out.println(sampleCalStr); int sampleCalResult = sampleCal(sampleCalStr); bracketStack.push(String.valueOf(sampleCalResult)); if(sampleCalResult < 0 && bracketStack.getStackSize() != 1) { //调整表达式结构 adjustExpression(bracketStack); } } else if(isMiddelBracketEnd(curChr)) { //中括号结束位置 String sampleCalStr = ""; String popStr = ""; bracketStack.pop(); // ( do { sampleCalStr = popStr + sampleCalStr; popStr = bracketStack.pop(); } while (!isMiddelBracketStart(popStr.charAt(0))); //System.out.println(sampleCalStr); int sampleCalResult = sampleCal(sampleCalStr); bracketStack.push(String.valueOf(sampleCalResult)); if(sampleCalResult < 0 && bracketStack.getStackSize() != 1) { //调整表达式结构 adjustExpression(bracketStack); } } else if(isBigBracketEnd(curChr)) { //大括号结束位置 String sampleCalStr = ""; String popStr = ""; bracketStack.pop(); // ( do { sampleCalStr = popStr + sampleCalStr; popStr = bracketStack.pop(); } while (!isBigBracketStart(popStr.charAt(0))); //System.out.println(sampleCalStr); int sampleCalResult = sampleCal(sampleCalStr); bracketStack.push(String.valueOf(sampleCalResult)); if(sampleCalResult < 0 && bracketStack.getStackSize() != 1) { //调整表达式结构 adjustExpression(bracketStack); } } } if(!bracketStack.isEmpt() && bracketStack.getStackSize() == 1) { //如果栈中只有一个值,直接输出答案 System.out.println(bracketStack.pop()); } else { //计算最终的表达式 String sampleCalStr = ""; String popStr = ""; while(!bracketStack.isEmpt()) { popStr = bracketStack.pop(); sampleCalStr = popStr + sampleCalStr; } //System.out.println(sampleCalStr); int result = sampleCal(sampleCalStr); System.out.println(result); } } } public static void main(String[] args) { Scanner in = new Scanner(System.in); Main m = new Main(); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case m.solution(in.nextLine()); } } /** * 对带有 - 号在后面的表达式调整格式, 例如5-3+9*6*-6调整成5-3-9*6*6方便计算 */ public void adjustExpression(Stack bracketStack) { Stack tmpStack = new Stack(); String topVal = bracketStack.pop(); int topValAbs = Math.abs(Integer.valueOf(topVal)); tmpStack.push(String.valueOf(topValAbs)); String chkFlag = bracketStack.pop(); if(!"+".equals(chkFlag) && !"-".equals(chkFlag)) { tmpStack.push(chkFlag); } while(isMutiDiv(chkFlag.charAt(0)) || isDigit(chkFlag.charAt(0))) { //如果是 * 或者 / //继续弹出栈 chkFlag = bracketStack.pop(); if(!"+".equals(chkFlag) && !"-".equals(chkFlag)) { tmpStack.push(chkFlag); } } //如果遇到 + - //则替换成 - + if("+".equals(chkFlag)) { tmpStack.push("-"); } else if("-".equals(chkFlag)) { tmpStack.push("+"); } while(!tmpStack.isEmpt()) { bracketStack.push(tmpStack.pop()); } } public static Integer calAB(String curCal) { if(curCal.contains("+")) { String[] paramArray = curCal.split("\\+"); int result = Integer.valueOf(paramArray[0]) + Integer.valueOf(paramArray[1]); return result; } else if(curCal.contains("-")) { String[] paramArray = curCal.split("\\-"); int result; if(paramArray.length == 3 && "".equals(paramArray[0])) { //表达式前面为 - result = - Integer.valueOf(paramArray[1]) - Integer.valueOf(paramArray[2]); } else { result = Integer.valueOf(paramArray[0]) - Integer.valueOf(paramArray[1]); } return result; } else if(curCal.contains("*")) { String[] paramArray = curCal.split("\\*"); int result = Integer.valueOf(paramArray[0]) * Integer.valueOf(paramArray[1]); return result; } else if(curCal.contains("/")) { String[] paramArray = curCal.split("\\/"); int result = Integer.valueOf(paramArray[0]) / Integer.valueOf(paramArray[1]); return result; } return null; } /** * 判断某个字符是否是数字 @param chkChar 要判断的字符 @return 是否是数字(true:数字 false:非数字) */ private static boolean isDigit(char chkChar) { if(chkChar >= '0' && chkChar <= '9' ) { return true; } return false; } private static boolean isAddSub(char chkChar) { if(chkChar == '+' || chkChar == '-') { return true; } return false; } private static boolean isMutiDiv(char chkChar) { if(chkChar == '*' || chkChar == '/') { return true; } return false; } private static boolean isContansBracket(String inputStr) { if(inputStr.contains("(") || inputStr.contains("[") || inputStr.contains("{") || inputStr.contains(")") || inputStr.contains("]") || inputStr.contains("}")) { return true; } return false; } /** * 判断某个字符是否是小括号的开始 * @param chkChar 要判断的字符 * @return 是否是小括号的开始(true:是 false:否) */ private static boolean isLittleBracketStart(char chkChar) { return chkChar == '(' ? true : false; } /** * 判断某个字符是否是小括号的结束 * @param chkChar 要判断的字符 * @return 是否是小括号的结束(true:是 false:否) */ private static boolean isLittleBracketEnd(char chkChar) { return chkChar == ')' ? true : false; } /** * 判断某个字符是否是中括号的开始 * @param chkChar 要判断的字符 * @return 是否是中括号的开始(true:是 false:否) */ private static boolean isMiddelBracketStart(char chkChar) { return chkChar == '[' ? true : false; } /** * 判断某个字符是否是中括号的结束 * @param chkChar 要判断的字符 * @return 是否是中括号的结束(true:是 false:否) */ private static boolean isMiddelBracketEnd(char chkChar) { return chkChar == ']' ? true : false; } /** * 判断某个字符是否是大括号的开始 * @param chkChar 要判断的字符 * @return 是否是大括号的开始(true:是 false:否) */ private static boolean isBigBracketStart(char chkChar) { return chkChar == '{' ? true : false; } /** * 判断某个字符是否是中括号的结束 * @param chkChar 要判断的字符 * @return 是否是大括号的结束(true:是 false:否) */ private static boolean isBigBracketEnd(char chkChar) { return chkChar == '}' ? true : false; } /** * 栈 */ static class Stack { //栈顶指针 private int stackIndex = 0; //保存栈的内容 private String[] elementData = new String[1000]; /** * 入栈 */ public void push(String element) { elementData[stackIndex] = element; stackIndex ++; } /** * 出栈 */ public String pop() { String result = elementData[stackIndex - 1]; stackIndex --; return result; } public boolean isEmpt() { return stackIndex == 0 ? true : false; } public int getStackSize() { return stackIndex; } } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; /** * @className: _4_9 * @author: Lian * @date: 2023-10-03 16:51 */ public class _5_0 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Stack<Character> operator = new Stack<>(); ArrayList<String> list = new ArrayList<>(); Map<Character, Integer> hashMap = new HashMap<>(); Stack<Double> stack = new Stack<>(); hashMap.put('(', 0); hashMap.put('-', 1); hashMap.put('+', 1); hashMap.put('*', 2); hashMap.put('/', 2); StringBuilder str = new StringBuilder(br.readLine().replace('{', '(').replace('}', ')').replace('[', '(').replace(']', ')')); int count = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '-') count++; } while (true) { for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '-') { if (i == 0 ||str.charAt(i)=='(') { str.insert(i + 2, ")"); str.insert(i, "(0"); break; } } } break; } char[] chars = str.toString().toCharArray(); for (int i = 0; i < chars.length; i++) { if (Character.isDigit(chars[i])) { int j = 0; while (i+j<chars.length&&Character.isDigit(chars[i + j])) { j++; } list.add(String.copyValueOf(chars, i, j)); i=i+j-1; continue; } if (chars[i] == '(') { operator.push(chars[i]); continue; } if (chars[i] == ')') { while (operator.peek() != '(') { char c = operator.pop(); list.add(String.valueOf(c)); } operator.pop(); continue; } if (operator.isEmpty()) { operator.push(chars[i]); continue; } while (!operator.isEmpty() && hashMap.get(chars[i]) <= hashMap.get(operator.peek())) { char c = operator.pop(); list.add(String.valueOf(c)); } operator.push(chars[i]); } while (!operator.isEmpty()) { list.add(String.valueOf(operator.pop())); } for (int i = 0; i < list.size(); i++) { if (Character.isDigit(list.get(i).charAt(0))) { stack.push(Double.valueOf(list.get(i))); continue; } double a = stack.pop(); double b = stack.pop(); if (list.get(i).equals("+")) { stack.push(a + b); continue; } if (list.get(i).equals("*")) { stack.push(a * b); continue; } if (list.get(i).equals("-")) { stack.push(b - a); continue; } if (list.get(i).equals("/")) { stack.push(b / a); } } System.out.printf("%.0f%n", stack.peek()); } }
public class Test01 { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextLine()) { String str = in.nextLine(); System.out.println(solution(str)); } } public static int solution(String str){ Stack<Integer> numStack = new Stack<>(); Stack<Character> pStack = new Stack<>(); for (int i = 0; i < str.length(); i++) { char a = str.charAt(i); //1、如果是括号 if(a=='('||a=='['||a=='{'){ pStack.push(a); int end = i; //找到括号的结尾 for (int j = i+1; j < str.length(); j++) { char k = str.charAt(j); if(k=='('||k=='['||k=='{'){ pStack.push(k); }else if(k==')'||k==']'||k=='}'){ pStack.pop(); if(pStack.isEmpty()||(pStack.peek()!='('&& pStack.peek()!='{'&& pStack.peek()!='[')){ end = j; break; } } } //递归计算括号中的结果push到数字栈中。 numStack.push(solution(str.substring(i+1,end))); //更新i的值。 i=end; }else if((i==0&&a=='-')||Character.isDigit(a)){ //2、找到的是数字,需要考虑负数开头。 String num = a+""; i++; while(i<str.length()&&Character.isDigit(str.charAt(i))){ num+=str.charAt(i); i++; } numStack.push(Integer.parseInt(num)); i--; }else{ //3、找到的是符号 if(!pStack.isEmpty()){ //如果找到的符号运算级小于等于栈中的符号,则先计算栈中的,如果大于栈中运算符,直接push。 if(a=='+'||a=='-'){ //遇到+、-需要将栈中的全部都计算了。 while(!pStack.isEmpty()){ numStack.push(operation(numStack.pop(),numStack.pop(),pStack.pop())); } }else if((a=='*'|| a=='/')&&(pStack.peek()=='*'||pStack.peek()=='/')){ numStack.push(operation(numStack.pop(),numStack.pop(),pStack.pop())); } } //将运算符压入符号栈。 pStack.push(a); } } //计算剩余元素的结果。 while(!pStack.isEmpty()){ numStack.push(operation(numStack.pop(),numStack.pop(),pStack.pop())); } return numStack.pop(); } public static int operation(int a , int b , Character p){ if(p=='+'){ return b+a; }else if(p=='-'){ return b-a; }else if(p=='*'){ return b*a; }else{ return b/a; } } }
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String express = in.next(); express = express.replace("{", "("); express = express.replace("[", "("); express = express.replace("}", ")"); express = express.replace("]", ")"); System.out.print(comput(dealParent(express))); } // 处理括号 public static String dealParent(String str) { ArrayList<Integer> parent = new ArrayList<>(); char[] carr = str.toCharArray(); String temp = str; StringBuilder sb = new StringBuilder(); for (int i = 0; i < carr.length; i++) { if (carr[i] == '(') { parent.add(i); } if (carr[i] == ')') { int start = parent.get(parent.size() - 1); String com = temp.substring(start + 1, i); String res = comput(com); sb.append(temp.substring(0, start)); // 添加空格补齐位数 int differ = i - start + 1 - res.length(); for (int j = 0; j < differ; j++) { sb.append(" "); } sb.append(res); if (i != carr.length - 1) { sb.append(temp.substring(i + 1, temp.length())); } temp = sb.toString(); sb.setLength(0); parent.remove(parent.size() - 1); } } return temp; } // 将字符串公式拆分成字符串数组 public static ArrayList<String> toStrArr(String str) { str = str.replace(" ", ""); ArrayList<String> exArr = new ArrayList<>(); char[] carr = str.toCharArray(); int start = 0; for (int i = 0; i < carr.length; i++) { if (i == 0 && carr[i] == '-') { continue; } if (carr[i] == '-' && (carr[i - 1] == '+' || carr[i - 1] == '*' || carr[i - 1] == '/' || carr[i - 1] == '-')) { continue; } if (carr[i] == '+' || carr[i] == '-' || carr[i] == '*' || carr[i] == '/') { exArr.add(str.substring(start, i)); exArr.add(str.substring(i, i + 1)); start = i + 1; } if (i == carr.length - 1) { exArr.add(str.substring(start, carr.length)); } } return exArr; } // 不带括号的计算 public static String comput(String str) { ArrayList<String> arr = toStrArr(str); for (int i = 0; i < arr.size(); i++) { if (arr.get(i).equals("*") || arr.get(i).equals("/")) { int a = Integer.parseInt(arr.get(i - 1)); int b = Integer.parseInt(arr.get(i + 1)); int res; if (arr.get(i).equals("*")) { res = a * b; } else { res = a / b; } arr.set(i + 1, String.valueOf(res)); arr.set(i, " "); arr.set(i - 1, " "); i++; } } while (arr.contains(" ")) { arr.remove(" "); } for (int i = 0; i < arr.size(); i++) { if (arr.get(i).equals("+") || arr.get(i).equals("-")) { int a = Integer.parseInt(arr.get(i - 1)); int b = Integer.parseInt(arr.get(i + 1)); int res; if (arr.get(i).equals("+")) { res = a + b; } else { res = a - b; } arr.set(i + 1, String.valueOf(res)); arr.set(i, " "); arr.set(i - 1, " "); i++; } } while (arr.contains(" ")) { arr.remove(" "); } return arr.get(0); } }
import java.util.*; // 大无语,怎么有这种这么繁琐的题啊 !!!! public class Main { public static int index = 0; public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.next(); System.out.println(getExpression(s)); } public static int getExpression(String s) { ArrayList<Integer> numArray = new ArrayList<>(); ArrayList<Character> signArray = new ArrayList<>(); HashMap<Character, Character> hp = new HashMap<>(); hp.put('[', ']'); hp.put('(', ')'); hp.put('{', '}'); int i = 0; int count = 0; StringBuilder strBuilder; while (i < s.length()) { if (i >= s.length()) break; char ch = s.charAt(i); if (ch == '(' || ch == '[' || ch == '{') { i++; count = 0; strBuilder = new StringBuilder(); while (i < s.length() && (s.charAt(i) != hp.get(ch) || count != 0)) { if (s.charAt(i) == ch) count++; if (s.charAt(i) == hp.get(ch)) count--; strBuilder.append(s.charAt(i)); i++; } i++; numArray.add(getExpression(strBuilder.toString())); }else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') { signArray.add(ch); i++; } else { int num = 0; while (i < s.length() && s.charAt(i) >= '0' && s.charAt(i) <= '9') { num = num * 10 + s.charAt(i) - '0'; i++; } numArray.add(num); } } Stack<Character> signStack = new Stack<>(); Stack<Integer> numStack = new Stack<>(); int indexArrayNum = 0, indexArraySign = 0; if (numArray.size() == signArray.size()) { numArray.set(0,-numArray.get(0)); indexArraySign++; } numStack.push(numArray.get(indexArrayNum++)); while (indexArraySign < signArray.size()) { char ch = signArray.get(indexArraySign++); if (ch == '+' || ch == '-') { signStack.push(ch); numStack.push(numArray.get(indexArrayNum++)); } else if (ch == '*') { int a = numStack.pop(); int b = numArray.get(indexArrayNum++); numStack.push(a * b); }else { int a = numStack.pop(); int b = numArray.get(indexArrayNum++); numStack.push(a / b); } } Stack<Character> signStack02 = new Stack<>(); Stack<Integer> numStack02 = new Stack<>(); while (!signStack.isEmpty()) { signStack02.push(signStack.pop()); } while (!numStack.isEmpty()) { numStack02.push(numStack.pop()); } while (!signStack02.isEmpty()) { int a = numStack02.pop(); int b = numStack02.pop(); char ch = signStack02.pop(); if (ch == '+') numStack02.push(a + b); else numStack02.push(a - b); } return numStack02.pop(); } }
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { String msg = in.nextLine(); msg = msg.replaceAll("\\{", "("); msg = msg.replaceAll("}", ")"); msg = msg.replaceAll("\\[", "("); msg = msg.replaceAll("]", ")"); while (msg.contains(")")) { msg = removeKuo(msg); } System.out.println(yunsuan(msg)); } } private static ArrayList<String> params = new ArrayList<>(); private static String removeKuo(String msg) { int end = msg.indexOf(")"); int start = 0; for (int i = end; i >= 0; i--) { if (msg.charAt(i) == '(') { start = i; break; } } String tmp = msg.substring(start + 1, end); tmp = yunsuan(tmp); return msg.replace(msg.substring(start, end + 1), tmp); } private static String yunsuan(String msg) { params.clear(); String tmp = ""; boolean hasDigit = false; for (int i = 0; i < msg.length(); i++) { if (Character.isDigit(msg.charAt(i))) { hasDigit = true; tmp = tmp + msg.charAt(i); } else { if (hasDigit) { params.add(tmp); params.add(String.valueOf(msg.charAt(i))); tmp = ""; hasDigit = false; } else { tmp = tmp + msg.charAt(i); } } } params.add(tmp); while (params.contains("*")) { int index = params.indexOf("*"); int pre = Integer.parseInt(params.remove(index - 1)); params.remove(index - 1); int next = Integer.parseInt(params.remove(index - 1)); params.add(index - 1, String.valueOf(pre * next)); } while (params.contains("/")) { int index = params.indexOf("/"); int pre = Integer.parseInt(params.remove(index - 1)); params.remove(index - 1); int next = Integer.parseInt(params.remove(index - 1)); params.add(index - 1, String.valueOf(pre / next)); } while (params.size() > 1) { int pre = Integer.parseInt(params.remove(0)); String fu = params.remove(0); int next = Integer.parseInt(params.remove(0)); params.add(0, String.valueOf("+".equals(fu) ? pre + next : pre - next)); } return params.get(0); } }
import java.util.Scanner; import java.util.List; import java.util.ArrayList; import java.util.Stack; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); //中括号、大括号全部转为小括号,方便处理 str = str.replace('[', '('); str = str.replace('{', '('); str = str.replace(']', ')'); str = str.replace('}', ')'); //1.将String类型的中缀表达式转成List<String>类型的中缀表达式 List<String> infixList = infixStringToList(str); //2.将List<String>类型的中缀表达式转成List<String>类型的后缀表达式 List<String> suffixList = infixToSuffix(infixList); //3.将List<String>类型的后缀表达式进行计算 int res = calculateSuffixNotation(suffixList); System.out.println(res); } //1.将String类型的中缀表达式转成List<String>类型 public static List<String> infixStringToList(String str) { List<String> list = new ArrayList<>(); int i = 0; while (i < str.length()) { if (str.charAt(i) == '+' || str.charAt(i) == '*' || str.charAt(i) == '/' || str.charAt(i) == '(' || str.charAt(i) == ')') { list.add(String.valueOf(str.charAt(i))); i++; } else if (str.charAt(i) == '-') {//考虑负数 if ((str.charAt(i) == '-' && str.charAt(i-1) == '(' && str.charAt(i+1)>= 48 && str.charAt(i+1)<= 57) || (str.charAt(i) == '-' && i == 0 && str.charAt(i+1)>= 48 && str.charAt(i+1)<= 57)) { list.add(String.valueOf(str.charAt(i))+String.valueOf(str.charAt(i+1))); i = i + 2; } else { list.add(String.valueOf(str.charAt(i))); i++; } } else { StringBuilder sb = new StringBuilder(); //考虑多位数 while (i < str.length() && str.charAt(i) >= 48 && str.charAt(i) <= 57) { sb.append(str.charAt(i)); i++; } list.add(sb.toString()); } } return list; } //2.将List<String>类型的中缀表达式转成List<String>类型的后缀表达式 public static List<String> infixToSuffix(List<String> infixList) { Stack<String> operationStack = new Stack<>(); List<String> tempResList = new ArrayList<>(); for (String s : infixList) { if (s.matches("\\d+")) { tempResList.add(s); } else if (s.matches("-\\d+")) { tempResList.add(s); } else if ("(".equals(s)) { operationStack.push(s); } else if (")".equals(s)) { while (!operationStack.peek().equals("(")) { tempResList.add(operationStack.pop()); } operationStack.pop();//去掉"(" } else { //如果s的运算优先级小于等于operationStack栈顶元素的优先级 //将operationStack栈顶元素弹出并加入tempResList中 //直到s可以入operationStack栈 while (operationStack.size() != 0 && operationPriority(s) <= operationPriority(operationStack.peek())) { tempResList.add(operationStack.pop()); } operationStack.push(s); } } while (operationStack.size() != 0) { tempResList.add(operationStack.pop()); } return tempResList; } //3.将List<String>类型的后缀表达式进行计算 //思想:遇到数字入栈,遇到操作符则将栈顶元素和栈顶元素的下一个元素进行操作符对应的运算后入栈 // 其中被减数和被除数是栈顶元素的下一个元素 public static int calculateSuffixNotation(List<String> suffixList) { Stack<Integer> stack = new Stack<>(); for (String s : suffixList) { if ("+".equals(s)) { stack.push(stack.pop()+stack.pop()); } else if ("-".equals(s)) { stack.push(-stack.pop()+stack.pop()); } else if ("*".equals(s)) { stack.push(stack.pop()*stack.pop()); } else if ("/".equals(s)) { int temp1 = stack.pop(); int temp2 = stack.pop(); stack.push(temp2 / temp1); } else { stack.push(Integer.parseInt(s)); } } //经过以上运算最终栈中只剩下一个元素 return stack.pop(); } public static int operationPriority(String operation) { if ("+".equals(operation) || "-".equals(operation)) { return 0; } else if ("*".equals(operation) || "/".equals(operation)) { return 1; } else { return -1; } } }