From 9fabcc111d79c9df621eca1108844fd0a5efc1a7 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 20 Oct 2024 22:34:36 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB1106.=20Parsing=20A=20Boolean?= =?UTF-8?q?=20Expression=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/parsing-a-boolean-expression/ Signed-off-by: Matej Focko --- go/parsing-a-boolean-expression.go | 54 ++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 go/parsing-a-boolean-expression.go diff --git a/go/parsing-a-boolean-expression.go b/go/parsing-a-boolean-expression.go new file mode 100644 index 0000000..6fc3ae9 --- /dev/null +++ b/go/parsing-a-boolean-expression.go @@ -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' +}