-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathremove_invalid_parentheses.go
61 lines (51 loc) · 1.13 KB
/
remove_invalid_parentheses.go
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
package graph
import "container/list"
// RemoveInvalidParentheses solves the problem in O(n^2) time and O(n) space.
func RemoveInvalidParentheses(input string) []string {
bfs := func(input string) []string {
output := make([]string, 0)
if input == "" {
return output
}
seen := make(map[string]struct{})
queue := list.New()
queue.PushBack(input)
seen[input] = struct{}{}
for queue.Len() != 0 {
input = queue.Remove(queue.Front()).(string)
if isValidParentheses(input) {
if len(output) > 0 && len(output[0]) != len(input) {
continue
}
output = append(output, input)
continue
}
for i := range len(input) {
if !(string(input[i]) == "(" || string(input[i]) == ")") {
continue
}
tmp := input[0:i] + input[i+1:]
if _, ok := seen[tmp]; !ok {
queue.PushBack(tmp)
seen[tmp] = struct{}{}
}
}
}
return output
}
return bfs(input)
}
func isValidParentheses(input string) bool {
count := 0
for i := range len(input) {
if input[i] == '(' {
count++
} else if input[i] == ')' {
count--
}
if count < 0 {
return false
}
}
return count == 0
}