go: add «1106. Parsing A Boolean Expression»

URL:	https://leetcode.com/problems/parsing-a-boolean-expression/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-10-20 22:34:36 +02:00
parent 49e73d89e6
commit 9fabcc111d
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,54 @@
package main
import (
arraystack "github.com/emirpasic/gods/v2/stacks/arraystack"
)
func parseBoolExpr(expression string) bool {
getRune := func(result bool) rune {
if result {
return 't'
}
return 'f'
}
st := arraystack.New[rune]()
for _, token := range expression {
if token == ',' || token == '(' {
// ignore delimiters and opening brackets
continue
}
// Handle closing of the operation
if token == ')' {
hasTrue, hasFalse := false, false
for top, has := st.Peek(); has && top != '!' && top != '&' && top != '|'; top, has = st.Peek() {
if top == 't' {
hasTrue = true
} else if top == 'f' {
hasFalse = true
}
st.Pop()
}
// evaluate the operator
op, _ := st.Pop()
if op == '!' {
st.Push(getRune(!hasTrue))
} else if op == '&' {
st.Push(getRune(!hasFalse))
} else {
st.Push(getRune(hasTrue))
}
continue
}
st.Push(token)
}
result, _ := st.Peek()
return result == 't'
}