当前位置:网站首页>【LeetCode】老虎证券面试-括号嵌套且满足优先级
【LeetCode】老虎证券面试-括号嵌套且满足优先级
2022-08-03 08:51:00 【凝眸伏笔】
LeetCode第20题:简单括号 力扣
题目描述:
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
例子:
示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
示例 4:
输入:s = "([)]"
输出:false
示例 5:
输入:s = "{[]}"
输出:true
解题思路:
- 如果 c 是左括号,则入栈 pushpush;
- 否则通过哈希表判断括号对应关系,若 stack 栈顶出栈括号 stack.pop() 与当前遍历括号 c 不对应,则提前返回 falsefalse。
解决边界问题:
- 栈 stack 为空: 此时 stack.pop() 操作会报错;因此,我们采用一个取巧方法,给 stack 赋初值 ?? ,并在哈希表 dic 中建立 key: '?',value:'?'key: ′? ′,value: ′? ′的对应关系予以配合。此时当 stack 为空且 c 为右括号时,可以正常提前返回 falsefalse;
- 字符串 s 以左括号结尾: 此情况下可以正常遍历完整个 s,但 stack 中遗留未出栈的左括号;因此,最后需返回 len(stack) == 1,以判断是否是有效的括号组合。
解题代码:
class Solution:
def isValid(self, s: str) -> bool:
stack = ['?']
kv = {'(':')', '[':']', '{':'}','?':'?'}
for ch in s:
if ch in kv.keys():
stack.append(ch)
elif stack and kv[stack.pop()] != ch: return False
res = False
if len(stack) == 1:
res = True
return res题目变种:
题目描述:
要求括号,满足:
- 成对出现
- 满足嵌套关系,{}中,可以有[], ()
解题思路:
在上述解题思路的基础上,在入栈的时候,做一个嵌套优先级的判断.
解题代码:
def isValid(s):
stack = ['?']
kv = {'(':')', '[':']', '{':'}','?':'?'}
for ch in s:
if ch in kv.keys():
if ch == '{' and len(stack) >=2 and stack[-1] in {'(', '['}:
return False
if ch == '[' and len(stack) >=2 and stack[-1] in {'('}:
return False
stack.append(ch)
elif kv[stack.pop()] != ch: return False
res = False
if len(stack) == 1:
res = True
return res边栏推荐
猜你喜欢

LINGO 18.0 software installation package download and installation tutorial

Using pipreqs export requirements needed for the project. TXT (rather than the whole environment)

English Grammar - Adverbial Clauses

Path Prefixes (倍增!树上の二分)

dflow入门2——Slices
![[Kaggle combat] Prediction of the number of survivors of the Titanic (from zero to submission to Kaggle to model saving and restoration)](/img/2b/d2f565d9221da094a9ccc30f506dc8.png)
[Kaggle combat] Prediction of the number of survivors of the Titanic (from zero to submission to Kaggle to model saving and restoration)

RSTP(端口角色+端口状态+工作机制)|||| 交换机接口分析

MySQL-TCL语言-transaction control language事务控制语言

What are pseudo-classes and pseudo-elements?The difference between pseudo-classes and pseudo-elements

word之个人设置
随机推荐
【微信小程序】底部有安全距离,适配iphone X等机型的解决方案
Nacos使用实践
dflow入门2——Slices
获取JDcookie的方法
pytorch one-hot 小技巧
【愚公系列】2022年07月 Go教学课程 026-结构体
ArcEngine (4) Use of MapControl_OnMouseDown
【LeetCode】101. Symmetric Binary Tree
MySQL-存储过程-函数-
多媒体数据处理实验3:图像特征提取与检索
10 minutes to get you started chrome (Google) browser plug-in development
C# 一周入门高级编程之《C#-继承》Day One
10分钟带你入门chrome(谷歌)浏览器插件开发
[Kaggle combat] Prediction of the number of survivors of the Titanic (from zero to submission to Kaggle to model saving and restoration)
图解Kernel Device Tree(设备树)的使用
系统io统计
ArcEngine (5) use the ICommand interface to achieve zoom in and zoom out
STP和RSTP的BPDU报文中flag位 对比+分析
基于二次型性能指标的燃料电池过氧比RBF-PID控制
行业洞察 | 如何更好的实现与虚拟人的互动体验?