MCPcopy Create free account
hub / github.com/austingebauer/go-leetcode / isValid

Function isValid

valid_parentheses_20/solution.go:3–40  ·  view source on GitHub ↗
(s string)

Source from the content-addressed store, hash-verified

1package valid_parentheses_20
2
3func isValid(s string) bool {
4 if s == "" {
5 return true
6 }
7
8 if len(s)%2 != 0 {
9 return false
10 }
11
12 stack := make([]string, len(s))
13 stackIdx := 0
14 for i := 0; i < len(s); i++ {
15 c := string(s[i])
16
17 // is an open character, so push on stack
18 if c == "(" || c == "{" || c == "[" {
19 stack[stackIdx] = c
20 stackIdx++
21 } else {
22 // initial closing character special case
23 if stackIdx == 0 {
24 return false
25 }
26
27 // is closing char, so pop one off stack to compare
28 stackIdx--
29 popC := stack[stackIdx]
30
31 if (c == ")" && popC != "(") ||
32 (c == "}" && popC != "{") ||
33 (c == "]" && popC != "[") {
34 return false
35 }
36 }
37 }
38
39 return stackIdx == 0
40}

Callers 1

Test_isValidFunction · 0.85

Calls

no outgoing calls

Tested by 1

Test_isValidFunction · 0.68