From 732fab4395de7a4965fcd380c0cebfd241683464 Mon Sep 17 00:00:00 2001 From: Luiz Felipe Limao Date: Sat, 25 Jun 2022 19:15:58 -0300 Subject: [PATCH] feature: add balanced brackets --- README.md | 3 ++- stack/balanced_brackets.go | 23 +++++++++++++++++++++++ stack/balanced_brackets_test.go | 15 +++++++++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 stack/balanced_brackets.go create mode 100644 stack/balanced_brackets_test.go diff --git a/README.md b/README.md index cbca464..59d6d01 100644 --- a/README.md +++ b/README.md @@ -44,13 +44,14 @@ Algorithms * [binary tree](https://en.wikipedia.org/wiki/Binary_search_tree) * [stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)) * [queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) + * [balanced_brackets](https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/) + #### Numerical * [gcd](https://en.wikipedia.org/wiki/Greatest_common_divisor) * [factorial](https://en.wikipedia.org/wiki/Factorial) * [fibonacci](https://en.wikipedia.org/wiki/Fibonacci_number) - Contribution ------------ diff --git a/stack/balanced_brackets.go b/stack/balanced_brackets.go new file mode 100644 index 0000000..723872f --- /dev/null +++ b/stack/balanced_brackets.go @@ -0,0 +1,23 @@ +package stack + +func isExpressionBalanced(text string) bool { + stack := make([]string, 0, len(text)) + + for i, char := range text { + if char == '(' { + stack = append(stack, string(char)) + } + if char == ')' { + stack = remove(stack, i-1) + } + } + + return len(stack) == 0 +} + +func remove(s []string, index int) []string { + if index >= len(s) { + return nil + } + return append(s[:index], s[index+1:]...) +} diff --git a/stack/balanced_brackets_test.go b/stack/balanced_brackets_test.go new file mode 100644 index 0000000..7da7f2b --- /dev/null +++ b/stack/balanced_brackets_test.go @@ -0,0 +1,15 @@ +package stack + +import "testing" + +func Test_isExpressionBalanced(t *testing.T) { + + if !isExpressionBalanced("(())") { + t.Error("[Error] Expression Balanced is wrong") + } + + if isExpressionBalanced("(()") { + t.Error("[Error] Expression Balanced is wrong") + } + +}