You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
954 B

package validparens
type stack struct {
store []rune
}
func (s *stack) Push(r rune) {
s.store = append(s.store, r)
}
func (s *stack) Pop() rune {
res := s.store[len(s.store)-1]
s.store = s.store[:len(s.store)-1]
return res
}
func (s *stack) Length() int {
return len(s.store)
}
func (s *stack) OnTop(r rune) bool {
if s.Length() == 0 {
return false
}
return s.store[len(s.store)-1] == r
}
func NewStack() stack {
store := make([]rune, 0)
return stack{
store: store,
}
}
func isValid(s string) bool {
history := NewStack()
for _, r := range s {
switch r {
case '{', '[', '(':
history.Push(r)
case ')':
if !history.OnTop('(') {
return false
}
history.Pop()
case ']':
if !history.OnTop('[') {
return false
}
history.Pop()
case '}':
if !history.OnTop('{') {
return false
}
history.Pop()
}
}
return history.Length() == 0
}
func IsValid(s string) bool {
return isValid(s)
}