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
|
class Solution { class Result {
boolean res;
int end;
Result(boolean res, int end) { this.res = res; this.end = end; } }
private Result parseBoolExpr(String expression, int start) { if (expression.charAt(start) == 'f') { return new Result(false, start + 1); } else if (expression.charAt(start) == 't') { return new Result(true, start + 1); } else if (expression.charAt(start) == '!') { Result result = parseBoolExpr(expression, start + 2); result.res = !result.res; result.end++; return result; } else if (expression.charAt(start) == '&') { Result finalResult = new Result(true, 0), result; start++; do { result = parseBoolExpr(expression, start + 1); if (!result.res) { finalResult.res = false; } start = result.end; } while (expression.charAt(result.end) == ','); finalResult.end = result.end + 1; return finalResult; } else if (expression.charAt(start) == '|') { Result finalResult = new Result(false, 0), result; start++; do { result = parseBoolExpr(expression, start + 1); if (result.res) { finalResult.res = true; } start = result.end; } while (expression.charAt(result.end) == ','); finalResult.end = result.end + 1; return finalResult; } else { throw new RuntimeException(); } }
public boolean parseBoolExpr(String expression) { return parseBoolExpr(expression, 0).res; }
public static void main(String[] args) { boolean res = new Solution().parseBoolExpr("!(&(&(!(&(f)),&(t),|(f,f,t)),&(t),&(t,t,f)))"); System.out.println(res); } }
|