-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid_parenthesis_test.go
More file actions
78 lines (64 loc) · 1.71 KB
/
Copy pathvalid_parenthesis_test.go
File metadata and controls
78 lines (64 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_isValidString(t *testing.T) {
testCases := []struct {
str string
expect bool
}{
{str: "(*))", expect: true},
{str: "(*", expect: true},
{str: "**************************************************))))))))))))))))))))))))))))))))))))))))))))))))))", expect: true},
{str: "(*(()*))", expect: true},
{str: "********", expect: true},
}
for _, tc := range testCases {
t.Run(tc.str, func(t *testing.T) {
res := checkValidString(tc.str)
assert.Equal(t, tc.expect, res)
})
}
}
func checkValidString(s string) bool {
n := len(s)
memo := make([][]int, n)
for i := range memo {
row := make([]int, n)
for j := 0; j < n; j++ {
row[j] = -1
}
memo[i] = row
}
return isValidString(0, 0, s, memo)
}
func isValidString(index int, openCount int, s string, memo [][]int) bool {
if index == len(s) {
return openCount == 0
}
if memo[index][openCount] != -1 {
// fmt.Println("memo", s[:index+1], "|", index, "|", openCount, "|", memo[index][openCount])
return memo[index][openCount] == 1
}
var isValid bool
if s[index] == '*' {
isValid = isValid || isValidString(index+1, openCount+1, s, memo)
if openCount > 0 {
isValid = isValid || isValidString(index+1, openCount-1, s, memo)
}
isValid = isValid || isValidString(index+1, openCount, s, memo)
} else {
if s[index] == '(' {
isValid = isValid || isValidString(index+1, openCount+1, s, memo)
} else if openCount > 0 {
isValid = isValid || isValidString(index+1, openCount-1, s, memo)
}
}
// fmt.Println(s[:index+1], "|", index, "|", openCount, "|", isValid)
memo[index][openCount] = 0
if isValid {
memo[index][openCount] = 1
}
return isValid
}