【LeetCode题解】20_有效的括号(Valid-Parentheses)
20_有效的括号(Valid-Parentheses)
描述
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 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)的更多相关文章
- LeetCode 20:有效的括号 Valid Parentheses
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. Given a string containing just the characters '(', ' ...
- LeetCode 20. 有效的括号(Valid Parentheses)
20. 有效的括号 20. Valid Parentheses 题目描述 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. 有效字符串需满足: 左括号必须 ...
- 【leetcode刷题笔记】Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- 【LeetCode每天一题】Longest Valid Parentheses(最长有效括弧)
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- LeetCode 1249. Minimum Remove to Make Valid Parentheses
原题链接在这里:https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/ 题目: Given a string s ...
- [Swift]LeetCode20. 有效的括号 | Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...
- [LeetCode]题解(python):022-Generate Parentheses
题目来源: https://leetcode.com/problems/generate-parentheses/ 题意分析: 题目输入一个整型n,输出n对小括号配对的所有可能性.比如说,如果输入3, ...
- [LeetCode]题解(python):020-Valid Parentheses
题目来源: https://leetcode.com/problems/valid-parentheses/ 题意分析: 这道题输入一段只包括括号的字符串,判断这个字符串是否已经配对.配对的规则是,每 ...
- LeetCode第[20]题(Java):Valid Parentheses
题目:有效的括号序列 难度:Easy 题目内容: Given a string containing just the characters '(', ')', '{', '}', '[' and ' ...
- LeetCode题解-20.有效的括号
题目 给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效. 有效字符串需满足: 左括号必须用相同类型的右括号闭合. 左括号必须以正确的顺序闭合. 示例 ...
随机推荐
- raiserror 的用法
if exists(select top 1 UserName from [dbo].[LJS_Test_User] where UserName=@UserName) begin raiserror ...
- jsp int转String or String转int 方法
将字串 String 转换成整数 int? A. 有两个方法: 1). int i = Integer.parseInt([String]); 或 i = Integer.parseInt([St ...
- Volo.Abp.EntityFrameworkCore.MySQL 使用
创建新项目 打开 https://cn.abp.io/Templates ,任意选择一个项目类型,然后创建项目,我这里创建了一个Web Api 解压项目,还原Nuget,项目目录如下: 首先我们来查看 ...
- .Net Core下使用Ajax,并传送参数到controllers
可以使用URL拼接方式方法传参 .cshtml部分 @section Scripts{ @{ await Html.RenderPartialAsync("_ValidationScript ...
- Windows 如何完整备份驱动
软件:DriverBackUp 系统环境:Windows7 首先将DriverBackUp.exe放到桌面,然后运行,我们会看到提示信息提示我们驱动程序被备份到了D盘 然后我们会看到备份界面 这里我们 ...
- Redis Sentinel初体验
自Redis增加Sentinel集群工具以来,本博主就从未尝试过使用该工具.最近在调研目前主流的Redis集群部署方案,所以详细地看了一遍官方对于Sentinel的介绍并在自己的台式机上完成了 ...
- [Swift]遍历字符串
Swift中无法再使用传统形式的for循环. //传统for循环形式不适用于Swift for(单次表达式;条件表达式;末尾循环体){中间循环体:} 字符串遍历方法1:使用该indices属性可以访问 ...
- Mysql6.0连接中的几个问题 Mysql6.xx
Mysql6.0连接中的几个问题 在最近做一些Javaweb整合时,因为我在maven官网查找的资源,使用的最新版,6.0.3,发现MySQL连接中的几个问题,总结如下: 1.Loading clas ...
- linux上搭建nginx+php+mysql环境详细讲解
1.mysql安装 #安装编译环境 yum install -y gcc gcc-c++ gcc-devel g++ g++-devel; yum install -y wget yum instal ...
- P4383 [八省联考2018]林克卡特树lct
题目链接 题意分析 一句话题意就是 : 让你选出\((k+1)\)条不相交的链 使得这些链的边权总和最大 (这些链可以是点) 我们考虑使用树形\(DP\) \(dp[i][j][0/1/2]\)表示以 ...