Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit b6daaab

Browse files
committed
1106 accepted.
1 parent 3fc52c9 commit b6daaab

File tree

2 files changed

+67
-1
lines changed

2 files changed

+67
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,67 @@
11
package problem1106
22

3-
func parseBoolExpr(expression string) bool {
3+
import "strings"
44

5+
func parseBoolExpr(exp string) bool {
6+
if exp == "t" {
7+
return true
8+
}
9+
if exp == "f" {
10+
return false
11+
}
12+
n := len(exp)
13+
symbol, exp := exp[0], exp[2:n-1]
14+
subs := split(exp)
15+
switch symbol {
16+
case '&':
17+
return and(subs)
18+
case '|':
19+
return or(subs)
20+
default:
21+
return not(exp)
22+
}
23+
}
24+
25+
func split(exp string) []string {
26+
count := 0
27+
isUnbracketed := func() bool {
28+
return count == 0
29+
}
30+
bytes := []byte(exp)
31+
for i, b := range bytes {
32+
switch b {
33+
case '(':
34+
count++
35+
case ')':
36+
count--
37+
case ',':
38+
if isUnbracketed() {
39+
bytes[i] = '@'
40+
}
41+
}
42+
}
43+
exp = string(bytes)
44+
return strings.Split(exp, "@")
45+
}
46+
47+
func or(exps []string) bool {
48+
for _, e := range exps {
49+
if parseBoolExpr(e) {
50+
return true
51+
}
52+
}
553
return false
654
}
55+
56+
func and(exps []string) bool {
57+
for _, e := range exps {
58+
if !parseBoolExpr(e) {
59+
return false
60+
}
61+
}
62+
return true
63+
}
64+
65+
func not(exp string) bool {
66+
return !parseBoolExpr(exp)
67+
}

Algorithms/1106.parsing-a-boolean-expression/parsing-a-boolean-expression_test.go

+5
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ var tcs = []struct {
1212
ans bool
1313
}{
1414

15+
{
16+
"&(&(|(f),&(&(&(&(t),&(!(t),!(|(f,f,t)),!(&(f))),|(f,f,t)),&(&(t),&(&(&(&(f),&(!(t),&(f),|(f)),&(!(&(f)),&(t),|(f,f,t))),|(t),&(!(t),!(|(f,f,t)),!(&(f)))),!(&(|(f,f,t),&(&(f),&(!(t),&(f),|(f)),&(!(&(f)),&(t),|(f,f,t))),&(t))),&(&(&(!(&(f)),|(t),&(!(t),!(|(f,f,t)),!(&(f)))),!(|(f,f,t)),&(t,t,f)),&(f),&(&(t),&(!(t),!(|(f,f,t)),!(&(f))),|(f,f,t)))),&(&(&(t,t,f),|(f,f,t),|(f)),!(&(t)),!(&(|(f,f,t),&(&(f),&(!(t),&(f),|(f)),&(!(&(f)),&(t),|(f,f,t))),&(t))))),&(&(!(&(f)),|(t),&(!(t),!(|(f,f,t)),!(&(f)))),!(|(f,f,t)),&(t,t,f))),!(&(f)),&(t)),!(&(|(f,f,t),&(&(f),&(!(t),&(f),|(f)),&(!(&(f)),&(t),|(f,f,t))),&(t)))),!(!(&(&(t,t,f),|(f,f,t),|(f)))),&(&(t),&(&(&(&(f),&(!(t),&(f),|(f)),&(!(&(f)),&(t),|(f,f,t))),|(t),&(!(t),!(|(f,f,t)),!(&(f)))),!(&(|(f,f,t),&(&(f),&(!(t),&(f),|(f)),&(!(&(f)),&(t),|(f,f,t))),&(t))),&(&(&(!(&(f)),|(t),&(!(t),!(|(f,f,t)),!(&(f)))),!(|(f,f,t)),&(t,t,f)),&(f),&(&(t),&(!(t),!(|(f,f,t)),!(&(f))),|(f,f,t)))),&(&(&(t,t,f),|(f,f,t),|(f)),!(&(t)),!(&(|(f,f,t),&(&(f),&(!(t),&(f),|(f)),&(!(&(f)),&(t),|(f,f,t))),&(t))))))",
17+
false,
18+
},
19+
1520
{
1621
"!(f)",
1722
true,

0 commit comments

Comments
 (0)