This commit is contained in:
VicRen
2020-12-15 09:16:01 +08:00
parent 9428031c4d
commit b0d252705a
2 changed files with 92 additions and 0 deletions

35
20201215/main.go Normal file
View File

@@ -0,0 +1,35 @@
package main
func main() {
}
func isValid(s string) bool {
if len(s)%2 == 1 {
return false
}
var stack []uint8
for i := 0; i < len(s); i++ {
c := s[i]
switch c {
case '(':
fallthrough
case '{':
fallthrough
case '[':
stack = append(stack, c)
default:
if len(stack) == 0 {
return false
}
last := stack[len(stack)-1]
if (last == '(' && c == ')') || last == '[' && c == ']' || last == '{' && c == '}' {
stack = stack[:len(stack)-1]
}
}
}
if len(stack) == 0 {
return true
}
return false
}

57
20201215/main_test.go Normal file
View File

@@ -0,0 +1,57 @@
package main
import "testing"
func Test_isValid(t *testing.T) {
type args struct {
s string
}
tests := []struct {
name string
args args
want bool
}{
{
"test1",
args{
"()",
},
true,
},
{
"test2",
args{
"()[]{}",
},
true,
},
{
"test3",
args{
"(]",
},
false,
},
{
"test4",
args{
"([)]",
},
false,
},
{
"test5",
args{
"{[]}",
},
true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isValid(tt.args.s); got != tt.want {
t.Errorf("isValid() = %v, want %v", got, tt.want)
}
})
}
}