feature: add balanced brackets

pull/39/head
Luiz Felipe Limao 2 years ago
parent 9e7a1904a5
commit 732fab4395

@ -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
------------

@ -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:]...)
}

@ -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")
}
}
Loading…
Cancel
Save