当前位置:网站首页>LeetCode#20.有效的括号
LeetCode#20.有效的括号
2022-06-22 20:06:00 【如风Zhhh】
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
示例 4:
输入:s = "([)]"
输出:false
示例 5:
输入:s = "{[]}"
输出:true
作者:力扣 (LeetCode)
链接:力扣
先进行分析我们了解到要满足这个有效的括号,必须要使题目中给出的三种可能出现的括号要左右量变闭合。所以使用栈的方法来完成这道题目还是比较合适的。此前我写过有关栈的知识的相关文章Python顺序表(列表)构造栈_如风Zhhh的博客-CSDN博客Python顺序表(列表)构造栈https://blog.csdn.net/qq_60926106/article/details/125286009?spm=1001.2014.3001.5502思路如下:
①.可以先进行一个大致的筛选,如果给出的字符串(这里我们用s来表示这个字符串)s的长度等于0或者是一个奇数,那么可以直接返回False了,因为如果括号想要形成闭合,s的长度只可能是偶数。
②.对于s不为0且是偶数的情况下,我们再进行如下判断:
1.遍历整个s,如果遍历出的元素 i (for i in s) 为"(" "{" "[" 中的任意一个,我们就可以把他们相对应的")" "}" "]" 压栈(前提是我们先创立一个列表来作为我们的栈)。如果 i 碰到的元素是")" "}" "]" ,我们可以进行出栈操作,看弹出元素是否与 i 相等,再进行判断。若相等,则继续循环,若不相等,直接返回False即可。
2.循环结束后,如果栈中元素为0,那么表示括号全部都得到了闭合,可以返回True,否则就返回False。
代码如下:
class Solution:
def isValid(self, s: str) -> bool:
if len(s)==0 or len(s)%2 != 0:
return False
stack=[]
for i in s:
if i=='(':
stack.append(')')
elif i=='{':
stack.append('}')
elif i=='[':
stack.append(']')
else:
if not stack:
return False
if i==stack.pop():
continue
return False
return stack==[]
边栏推荐
- Set up your own website (12)
- 84- I am on Internet & lt; 52 SQL statement performance optimization strategies & gt; Some views of
- [redis]配置文件
- 杰理之AUX 模式使用 AUX1或者 AUX2通道时,程序会复位问题【篇】
- Win10 installation net3.5. docx
- 使用Charles抓包
- 【876. 链表的中间结点】
- Numpy learning notes (6) -- sum() function
- 第027讲:集合:在我的世界里,你就是唯一 | 课后测试题及答案
- CVPR2022 | 海德堡大学《深度视觉相似性与度量学习》教程
猜你喜欢

2022 question bank and simulated examination for work license of main principals of hazardous chemical business units

Set up your own website (12)

Numpy learning notes (6) -- sum() function

杰理之开启四声道通话近端卡顿问题【篇】

【142. 环形链表 II】
![[redis] publish and subscribe](/img/50/0c2fbbb8f56fccdd3222b77efdd723.png)
[redis] publish and subscribe

杰理之外挂 4M 的 flash 在 PC 上查看大小只有 1M 的处理方法【篇】

2022化工自动化控制仪表考试练习题及在线模拟考试

Ultrafast transformers | redesign vit with res2net idea and dynamic kernel size, surpassing mobilevit
![[redis]redis6 transaction operations](/img/50/639867a2fcb92082ea262a8a19bb68.png)
[redis]redis6 transaction operations
随机推荐
70 root cause analysis Oracle database sudden performance problems, who will take the blame
苹果Objective-C源代码
[redis] publish and subscribe
Adblock屏蔽百度热搜
88- widely circulated parameter optimization, honey or poison?
2022化工自动化控制仪表考试练习题及在线模拟考试
RealNetworks vs. 微软:早期流媒体行业之争
las 点云创建网格
第014-15讲:字符串 (见小甲鱼新版27讲-32讲)| 课后测试题及答案
Pytorch's model saving, loading and continuing training
Baijia forum in the 13th year of Yongzheng (lower part)
2022危险化学品经营单位主要负责人上岗证题库及模拟考试
[redis]集群与常见错误
杰理之在music模式下提示音使用打断模式无法播放的问题【篇】
Apple corefoundation source code
Remote access to raspberry pie via the Internet.
[palindrome structure of or36 linked list]
【20. 有效的括号】
[redis]Redis6的事务操作
【CM11 链表分割】