| 1 | package valid_parentheses_20 |
| 2 | |
| 3 | func 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 | } |