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
| package main
import ( "fmt" )
func isValid(s string) bool { stack := []rune{} pairs := map[rune]rune{ ')': '(', ']': '[', '}': '{', } for _, c := range s { if _, ok := pairs[c]; ok { if len(stack) == 0 || stack[len(stack)-1] != pairs[c] { return false } stack = stack[:len(stack)-1] } else { stack = append(stack, c) } } return len(stack) == 0 }
func main() { testCases := []struct { s string expected bool }{ {"()", true}, {"()[]{}", true}, {"(]", false}, {"([)]", false}, {"", true}, {"(", false}, {")", false}, }
for i, tc := range testCases { result := isValid(tc.s) fmt.Printf("Test Case %d: Input: s = %q\n", i+1, tc.s)
if result == tc.expected { fmt.Printf("Output: %v, PASS\n", result) } else { fmt.Printf("Output: %v, FAIL (Expected: %v)\n", result, tc.expected) } } }
|