-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathParsingABooleanExpression.java
49 lines (43 loc) · 1.29 KB
/
ParsingABooleanExpression.java
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
package com.smlnskgmail.jaman.leetcodejava.hard;
// https://leetcode.com/problems/parsing-a-boolean-expression/
public class ParsingABooleanExpression {
private final String input;
public ParsingABooleanExpression(String input) {
this.input = input;
}
public boolean solution() {
return calc(input, 0, input.length() - 1);
}
private boolean calc(String e, int l, int h) {
if (l == h) {
return e.charAt(l) == 't';
}
char op = e.charAt(l);
int c = 0;
int prev = l + 2;
boolean result = op != '|';
for (int i = l + 1; i <= h; i++) {
char v = e.charAt(i);
if (v == '(') {
c++;
} else if (v == ')') {
c--;
}
if ((c == 1 && v == ',') || (c == 0 && v == ')')) {
boolean next = calc(e, prev, i - 1);
prev = i + 1;
switch (op) {
case '|':
result |= next;
break;
case '&':
result &= next;
break;
default:
result = !next;
}
}
}
return result;
}
}