package main
/*
* @lc app=leetcode.cn id=20 lang=golang
*
* [20] 有效的括号
*/
// @lc code=start
type (
Stack struct {
top *node
length int
}
node struct {
value int
prev *node
}
)
// Create a new stack
func New() *Stack {
return &Stack{nil, 0}
}
// Return the number of items in the stack
func (this *Stack) Len() int {
return this.length
}
// View the top item on the stack
func (this *Stack) Peek() int {
if this.length == 0 {
return 0
}
return this.top.value
}
// Pop the top item of the stack and return it
func (this *Stack) Pop() int {
if this.length == 0 {
return 0
}
n := this.top
this.top = n.prev
this.length--
return n.value
}
// Push a value onto the top of the stack
func (this *Stack) Push(value int) {
n := &node{value, this.top}
this.top = n
this.length++
}
// 123 {
// 91 [
// 40 (
// 41 )
// 93 ]
// 125 }
//主函数
func isValid(s string) bool {
bracket := New()
for _, v := range s {
switch v {
case 123:
bracket.Push(int(v))
case 91:
bracket.Push(int(v))
case 40:
bracket.Push(int(v))
case 41:
topValue := bracket.Pop()
if (int(v) - topValue) != 1 {
return false
}
case 93:
topValue := bracket.Pop()
if (int(v) - topValue) != 2 {
return false
}
case 125:
topValue := bracket.Pop()
if (int(v) - topValue) != 2 {
return false
}
}
}
if bracket.Len() != 0 {
return false
}
return true
}
// @lc code=end