首页 > 其他 > 详细

有效的括号

时间:2020-06-27 19:17:25      阅读:70      评论:0      收藏:0      [点我收藏+]

有效的括号

给定一个只包括 ‘(‘,‘)‘,‘{‘,‘}‘,‘[‘,‘]‘?的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true
示例?2:

输入: "()[]{}"
输出: true
示例?3:

输入: "(]"
输出: false
示例?4:

输入: "([)]"
输出: false
示例?5:

输入: "{[]}"
输出: true

题解

func isValid(s string) bool {
	l := len(s)
	stack := make(Stack,0,l)
	for i:=0;i<l;i++ {
		t := s[i:i+1]
		if t == "(" || t == "[" || t == "{" {
			stack.Push(t)
		} else {
			t2,_ := stack.Pop()
			if !( ( t2 == "(" && t == ")" ) || ( t2 == "[" && t == "]") || ( t2 == "{" && t == "}" ) ) {
				return false
			}
		}
	}
	if len(stack) !=0 {
		return false
	}

	return true
}



type Stack []string

func (stack Stack) Len() int {
	return len(stack)
}

func (stack Stack) IsEmpty() bool  {
	return len(stack) == 0
}

func (stack Stack) Cap() int {
	return cap(stack)
}

func (stack *Stack) Push(value string)  {
	*stack = append(*stack, value)
}

func (stack Stack) Top() (interface{}, error)  {
	if len(stack) == 0 {
		return nil, errors.New("Out of index, len is 0")
	}
	return stack[len(stack) - 1], nil
}

func (stack *Stack) Pop() (string, error)  {
	theStack := *stack
	if len(theStack) == 0 {
		return "", errors.New("Out of index, len is 0")
	}
	value := theStack[len(theStack) - 1]
	*stack = theStack[:len(theStack) - 1]
	return value, nil
}

code

有效的括号

原文:https://www.cnblogs.com/followyou/p/13199386.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!