来源
https://leetcode-cn.com/problems/valid-parentheses
问题描述
//给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
//有效字符串需满足:
//左括号必须用相同类型的右括号闭合。
//左括号必须以正确的顺序闭合。
//注意空字符串可被认为是有效字符串。
//示例 1:
//
//输入: “()”
//输出: true
//示例 2:
//
//输入: “()[]{}”
//输出: true
//示例 3:
//
//输入: “(]”
//输出: false
//示例 4:
//
//输入: “([)]”
//输出: false
//示例 5:
//
//输入: “{[]}”
//输出: true
func Push(res *[]byte, s byte) {
temp := *res
temp = append(temp, s)
*res = temp
}
func Pop(res *[]byte) byte {
temp := *res
bc := temp[len(temp)-1]
*res = temp[:len(temp)-1]
return bc
}
func IsEmpty(res *[]byte) bool {
return len(*res) == 0
}
func isValid(s string) bool {
stack := new([]byte)
for _, v := range s {
if v == '(' {
Push(stack, ')')
} else if v == '{' {
Push(stack, '}')
} else if v == '[' {
Push(stack, ']')
} else if IsEmpty(stack) {
return false
} else if c := Pop(stack); int(c) != int(v) {
return false
}
}
return IsEmpty(stack)
}
利用FIFO,先进后出。解决括号必须成对出现,必须得出现左边才能出现右边,利用这个解决即可