Matej Focko
9fabcc111d
URL: https://leetcode.com/problems/parsing-a-boolean-expression/ Signed-off-by: Matej Focko <me@mfocko.xyz>
54 lines
980 B
Go
54 lines
980 B
Go
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'
|
|
}
|