1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| package org.stone.study.algo.ex202411;
import java.util.Scanner; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern;
public class MaxExprValue { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); long ans = maxExprValue(str); System.out.println(ans); }
public static long maxExprValue(String str) { int ans = 0; String regex = "\\d+(?:[-+*]\\d+)*"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(str);
String longestExpr = ""; int maxLen = 0; while (matcher.find()) { String expr = matcher.group(); if(expr.length() > maxLen) { longestExpr = expr; maxLen = expr.length(); } }
if(longestExpr.isEmpty()) { return 0; }
try { return evaluateExpr(longestExpr); } catch (Exception e) { return 0; } }
private static long evaluateExpr(String expr) { Stack<Long> numStack = new Stack<>(); Stack<Character> opStack = new Stack<>(); int n = expr.length(); long num = 0; boolean hasNum = false;
for(int i = 0; i < n; i++) { char c = expr.charAt(i); if(Character.isDigit(c)) { num = num * 10 + (c - '0'); hasNum = true; } else { if(!hasNum) { throw new RuntimeException("Invalid expression"); } numStack.push(num); num = 0; hasNum = false; while(!opStack.isEmpty() && priority(opStack.peek()) >= priority(c)) { numStack.push(applyOp(numStack.pop(), numStack.pop(), opStack.pop())); } opStack.push(c); } } if(hasNum) { numStack.push(num); } while(!opStack.isEmpty()) { numStack.push(applyOp(numStack.pop(), numStack.pop(), opStack.pop())); }
return numStack.pop(); }
private static long applyOp(long b, long a, char op) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; default: throw new RuntimeException("Invalid operator"); } }
private static int priority(char op) { switch (op) { case '+': case '-': return 1; case '*': return 2; default: return 0; } } }
|