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:
parent
49e73d89e6
commit
9fabcc111d
1 changed files with 54 additions and 0 deletions
54
go/parsing-a-boolean-expression.go
Normal file
54
go/parsing-a-boolean-expression.go
Normal 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'
|
||||
}
|
Loading…
Reference in a new issue