Valid Parentheses
LeetCode 20 · View on LeetCode
Push opening brackets onto the stack. When you hit a closing bracket, pop and check if it matches. If the stack is empty at the end, the string is valid.
package main
import "fmt"
func isValid(s string) bool {
stack := []byte{}
pairs := map[byte]byte{')': '(', ']': '[', '}': '{'}
for i := 0; i < len(s); i++ {
if s[i] == '(' || s[i] == '[' || s[i] == '{' {
stack = append(stack, s[i])
} else {
if len(stack) == 0 || stack[len(stack)-1] != pairs[s[i]] {
return false
}
stack = stack[:len(stack)-1]
}
}
return len(stack) == 0
}
func main() {
fmt.Println(isValid("()[]{}")) // true
fmt.Println(isValid("(]")) // false
fmt.Println(isValid("{[]}")) // true
fmt.Println(isValid("([)]")) // false
}