Middle+
// The input is a string s containing only the characters '(', ')', '[', ']' // Determine if the input string is valid. // The string is valid if: // - All open brackets are closed by brackets of the same type. // - Brackets are closed in the correct order. // - Each closing bracket has a corresponding open bracket of the same type // () // func isValid(s string) bool { // }
sobes.tech AI
Answer from AI
To check the validity of a string with brackets, you can use a stack. The idea is that when you encounter an opening bracket, you push it onto the stack, and when you encounter a closing bracket, you check if it matches the last opened one (the top element of the stack). If not, the string is invalid. At the end, the stack should be empty.
Example in Go:
type stack []rune
func (s *stack) push(r rune) {
*s = append(*s, r)
}
func (s *stack) pop() (rune, bool) {
if len(*s) == 0 {
return ' ', false
}
index := len(*s) - 1
elem := (*s)[index]
*s = (*s)[:index]
return elem, true
}
func isValid(s string) bool {
var st stack
pairs := map[rune]rune{')': '(', ']': '['}
for _, ch := range s {
switch ch {
case '(', '[':
st.push(ch)
case ')', ']':
top, ok := st.pop()
if !ok || pairs[ch] != top {
return false
}
}
}
return len(st) == 0
}