前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode-20. Valid Parentheses | 有效的括号

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

作者头像
Zoctopus
发布2021-02-25 17:15:08
3710
发布2021-02-25 17:15:08
举报

题目

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.
代码语言:javascript
复制
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

代码语言:javascript
复制
//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
}

执行结果:

代码语言:javascript
复制
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.

解法二:栈

代码语言:javascript
复制
//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
}

执行结果:

代码语言:javascript
复制
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.
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-02-07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 题解
    • 解法一:使用strings.Replace替换为空
      • 解法二:栈
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档