当前位置:网站首页>栈与队列——20. 有效的括号
栈与队列——20. 有效的括号
2022-07-24 13:53:00 【向着百万年薪努力的小赵】
1 题目描述
给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
2 题目示例
示例 1:
输入:s = “()”
输出:true
示例 2:
输入:s = “()[]{}”
输出:true
示例 3:
输入:s = “(]”
输出:false
示例 4:
输入:s = “([)]”
输出:false
示例 5:
输入:s = “{[]}”
输出:true
3 题目提示
1 <= s.length <= 104
s 仅由括号 ‘()[]{}’ 组成
4 思路
判断括号的有效性可以使用「栈」这—数据结构来解决。
我们遍历给定的字符串s。当我们遇到一个左括号时,我们会期望在后续的遍历中,有一个相同类型的右括号将其闭合。由于后遇到的左括号要先闭合,因此我们可以将这个左括号放入栈顶。当我们遇到一个右括号时,我们需要将一个相同类型的左括号闭合。此时,我们可以取出栈顶的左括号并判断它们是否是相同类型的括号。如果不是相同的类型,或者栈中并没有左括号,那么字符串s无效,返回False。为了快速判断括号的类型,我们可以使用哈希表存储每—种括号。哈希表的键为右括号,值为相同类型的左括号。
在遍历结柬后,如果栈中没有左括号,说明我们将字符串s中的所有左括号闭合,返回True,否则返回False。
注意到有效字符串的长度—定为偶数,因此如果字符串的长度为奇数,我们可以直接返回False,省去后续的遍历判断过程。
5 我的答案
方法一:
class Solution {
public boolean isValid(String s) {
int n = s.length();
if (n % 2 == 1) {
return false;
}
Map<Character, Character> pairs = new HashMap<Character, Character>() {
{
put(')', '(');
put(']', '[');
put('}', '{');
}};
Deque<Character> stack = new LinkedList<Character>();
for (int i = 0; i < n; i++) {
char ch = s.charAt(i);
if (pairs.containsKey(ch)) {
if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
return false;
}
stack.pop();
} else {
stack.push(ch);
}
}
return stack.isEmpty();
}
}
边栏推荐
猜你喜欢

Network security -- man in the middle attack penetration test

【无标题】

Network security - function bypass injection

rhcsa第六次笔记

Network security - Web information collection

2021-07-09

为什么函数式接口 Comparator 中有 “两个抽象方法”?

WSDM 22 | graph recommendation based on hyperbolic geometry

论文笔记:Swin-Unet: Unet-like Pure Transformer for MedicalImage Segmentation

使用树莓派做Apache2 HA实验
随机推荐
Browser type judgment
Flink comprehensive case (IX)
第六章 总线
How to verify the domain name after applying for SSL digital certificate?
An error is reported when using activiti to create a database table,
Sringboot plugin framework implements pluggable plug-in services
Network security - Web penetration testing
Flinktable & SQL (VII)
网络安全——Cookie注入
CSDN garbage has no bottom line!
Network security - use exchange SSRF vulnerabilities in combination with NTLM trunking for penetration testing
Swarm intelligence collaborative obstacle avoidance method inspired by brain attention mechanism
Browser failed to get cookies, browser solution
自动化运维之Ansible安装部署
The R language uses the sort function to sort vector data and return the actually sorted data (ascending by default)
网络安全——使用Exchange SSRF 漏洞结合NTLM中继进行渗透测试
Sringboot-plugin-framework 实现可插拔插件服务
rhce第一次作业
Matlab program for natural gas flow calculation
R语言tidyr包的gather函数将从宽表转化为长表(宽表转化为长表)、第一个参数指定原多个数据列名称生成的新数据列名称、第二个参数指定原表内容值、第三个和第四个参数通过列索引指定不变的列名称列表