LeetCode-20. Valid Parentheses | 有效的括号

题目

LeetCode
LeetCode-cn

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  • Open brackets must be closed by the same type of brackets.
  • Open brackets must be closed in the correct order.
Example 1:

Input: s = "()"
Output: true
Example 2:

Input: s = "()[]{}"
Output: true
Example 3:

Input: s = "(]"
Output: false
Example 4:

Input: s = "([)]"
Output: false
Example 5:

Input: s = "{[]}"
Output: true
 

Constraints:
1 <= s.length <= 104
s consists of parentheses only '()[]{}'.

题解

这道题是经典的考察栈的题目。

解法一:使用strings.Replace替换为空

直接用strings.Replace方法,将()、[]、{}这样的字符串替换为空,如果最后全都可以替换掉,说明是有效字符串,返回true,否则返回false

//Go
func isValid(s string) bool {
    if len(s)%2 == 1 {
		return false
	}
	for len(s) != 0 {
		temp := s
		s = strings.Replace(s, "()", "", -1)
		s = strings.Replace(s, "[]", "", -1)
		s = strings.Replace(s, "{}", "", -1)

		if s == temp {
			return false
		}
	}

	return true
}

执行结果:

leetcode-cn执行:
执行用时:4 ms, 在所有 Go 提交中击败了6.50%的用户
内存消耗:7.1 MB, 在所有 Go 提交中击败了5.26%的用户

leetcode执行:
Runtime: 4 ms, faster than 5.19% of Go online submissions for Valid Parentheses.
Memory Usage: 7 MB, less than 7.32% of Go online submissions for Valid Parentheses.

解法二:栈

//Go
func isValid(s string) bool {
    //考虑空字符串的特殊情况
    if s == "" {
		return true
	}
    //定义一个栈
	stack := make([]int32, len(s))
    length := 0
    //判断括号是否匹配
    for _,v := range s {
        if v == '(' || v == '[' || v == '{' {
            //左括号,入栈
            stack[length] = v
            length++
        } else {
            //右括号,比较栈顶,匹配则移除,不匹配就返回false
            if length == 0 {
                return false
            }
            if (v == ')' && stack[length-1] == '(') || (v == ']' && stack[length-1] == '[') || (v == '}' && stack[length-1] == '{') {
                length--
            } else {
                return false
            }
        }
    }

    return length == 0
}

执行结果:

leetcode-cn执行:
执行用时:0 ms, 在所有 Go 提交中击败了100.00%的用户
内存消耗:2 MB, 在所有 Go 提交中击败了72.86%的用户

leetcode执行:
Runtime: 0 ms, faster than 100.00% of Go online submissions for Valid Parentheses.
Memory Usage: 2 MB, less than 98.88% of Go online submissions for Valid Parentheses.
         
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明。
    
特此声明:所有评论和私信都会在第一时间回复。也欢迎园子里和园子外的大大们指正错误,共同进步。或者直接私信我 (^∀^)
    
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是作者坚持原创和持续写作的最大动力!

您的资助是我最大的动力!
金额随意,欢迎来赏!

如果,您认为阅读这篇博客让您有些收获,不妨点击一下右下角的推荐按钮。
如果,您希望更容易地发现我的新博客,不妨点击一下绿色通道的关注我

如果,想给予我更多的鼓励,求打

本博客的所有打赏均将用于博主女朋友的化妆品购买以及养肥计划O(∩_∩)O。我是【~不会飞的章鱼~】!

联系或打赏博主【~不会飞的章鱼~】!https://www.cnblogs.com/OctoptusLian/

原文地址:https://www.cnblogs.com/OctoptusLian/p/14387013.html