20_有效的括号(Valid-Parentheses)

描述

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

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true

示例 2:

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

示例 3:

输入: "(]"
输出: false

示例 4:

输入: "([)]"
输出: false

示例 5:

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

解法

思路

遍历字符串的每个字符,如果字符是左半边的括号(即 ([ 或者{),将字符压入栈;如果字符是右半边括号(即 )] 或者 }),此时首先判断堆栈是否为空,如果栈为空,则该字符无法找到匹配的括号,返回 false,如果栈不为空,则弹出栈顶元素并与之比较,如果两个字符不相同,同样返回 false。最后,遍历完整个字符串后,还需要判断堆栈是否为空,如果为空,则是有效的括号,反之则为无效的括号。

Java 实现

class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i=0; i<s.length(); i++) {
char c = s.charAt(i); if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else {
if (stack.empty()) {
return false;
} char topChar = stack.pop();
if (c == ')' && topChar != '(') {
return false;
}
if (c == ']' && topChar != '[') {
return false;
}
if (c == '}' && topChar != '{') {
return false;
}
}
} return stack.isEmpty();
}
}

改进版:

class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(') {
stack.push(')');
} else if (c == '[') {
stack.push(']');
} else if (c == '{') {
stack.push('}');
} else if (stack.isEmpty() || c != stack.pop()) {
return false;
}
}
return stack.isEmpty();
}
}

Python 实现

实现1:

class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = list()
for si in s:
if si == '(':
stack.append(')')
elif si == '[':
stack.append(']')
elif si == '{':
stack.append('}')
elif len(stack) == 0 or si != stack.pop():
return False
return len(stack) == 0

实现 2(借助字典):

class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = list()
dict = {'(': ')', '[': ']', '{': '}'}
for c in s:
if c in dict.keys():
stack.append(dict[c])
elif c in dict.values():
if len(stack) == 0 or c != stack.pop():
return False
else:
False
return len(stack) == 0

复杂度分析

  • 时间复杂度:\(O(n)\),其中 \(n\) 表示字符串的长度
  • 空间复杂度:\(O(n)\),最坏的情况下,堆栈需要存放字符串的所有字符

【LeetCode题解】20_有效的括号(Valid-Parentheses)的更多相关文章

  1. LeetCode 20:有效的括号 Valid Parentheses

    给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. Given a string containing just the characters '(', ' ...

  2. LeetCode 20. 有效的括号(Valid Parentheses)

    20. 有效的括号 20. Valid Parentheses 题目描述 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. 有效字符串需满足: 左括号必须 ...

  3. 【leetcode刷题笔记】Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  4. 【LeetCode每天一题】Longest Valid Parentheses(最长有效括弧)

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  5. LeetCode 1249. Minimum Remove to Make Valid Parentheses

    原题链接在这里:https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/ 题目: Given a string s ...

  6. [Swift]LeetCode20. 有效的括号 | Valid Parentheses

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...

  7. [LeetCode]题解(python):022-Generate Parentheses

    题目来源: https://leetcode.com/problems/generate-parentheses/ 题意分析: 题目输入一个整型n,输出n对小括号配对的所有可能性.比如说,如果输入3, ...

  8. [LeetCode]题解(python):020-Valid Parentheses

    题目来源: https://leetcode.com/problems/valid-parentheses/ 题意分析: 这道题输入一段只包括括号的字符串,判断这个字符串是否已经配对.配对的规则是,每 ...

  9. LeetCode第[20]题(Java):Valid Parentheses

    题目:有效的括号序列 难度:Easy 题目内容: Given a string containing just the characters '(', ')', '{', '}', '[' and ' ...

  10. LeetCode题解-20.有效的括号

    题目 给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效. 有效字符串需满足: 左括号必须用相同类型的右括号闭合. 左括号必须以正确的顺序闭合. 示例 ...

随机推荐

  1. 在TFS 2013的敏捷组合管理中添加积压工作

    在TFS提供的三套默认模板中,组合管理(Portfolio Management)只包含功能(Feature)和要求这个两个积压工作.你可以参考下面的文档,学会如何在积压工作中添加额外的工作项类型. ...

  2. 使用CDI+制作支持半透明的Panle

    创建一个自定义控件程序集,并修改父类为Panle,添加如下代码: public partial class OpaqueLayer : Panel { private Color transparen ...

  3. ES6学习之ES5之后新增的字符串方法

    1.字符串模板:用法:`${变量名}` (好像是C#6.0中也引入了类似的方法.C#中的用法:$"我是{变量名}" ---> $"我叫{name}" ,相 ...

  4. Android 获取 content layout

    if (findViewById(android.R.id.content) instanceof ViewGroup) { ViewGroup mainView = ((ViewGroup)find ...

  5. 解决 UnicodeEncodeError: 'ascii' codec can't encode characters in position 问题

    在开头加上 import sys reload(sys) sys.setdefaultencoding( "utf-8" ) Python自然调用ascii编码解码程序去处理字符流 ...

  6. AI下载步骤

    ai下载地址:https://www.adobe.com/cn/creativecloud/catalog/desktop.html?promoid=PTYTQ77P&mv=other 破解器 ...

  7. Codechef:Fibonacci Number/FN(二次剩余+bsgs)

    题面 传送门 前置芝士 \(bsgs\),\(Cipolla\) 题解 因为题目保证\(p\bmod 10\)是完全平方数,也就是说\(p\bmod 5\)等于\(1\)或\(-1\),即\(5\)是 ...

  8. Redis Sentinel初体验

        自Redis增加Sentinel集群工具以来,本博主就从未尝试过使用该工具.最近在调研目前主流的Redis集群部署方案,所以详细地看了一遍官方对于Sentinel的介绍并在自己的台式机上完成了 ...

  9. 爬虫之chrome浏览器的使用方法

    chrome浏览器使用方法介绍 1. 新建隐身窗口 1.1 为什么需要新建隐身窗口 在打开隐身窗口的时候,第一次请求某个网站是没有携带cookie的,和代码请求一个网站一样,不携带cookie.这样就 ...

  10. 校验 CentOS 7 镜像文件

    验证镜像文件的原因 CentOS Vault(http://vault.centos.org/)页脚的镜像站链接上有段英文,指出页脚的镜像站链接不受 CentOS 团队的监控,除此之外还有一个原因就是 ...