feature: add balanced brackets
parent
9e7a1904a5
commit
732fab4395
@ -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…
Reference in New Issue