当前位置:网站首页>【刷题记录】20. 有效的括号
【刷题记录】20. 有效的括号
2022-07-24 18:12:00 【InfoQ】
一、题目描述
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
输入:s = "()"
输出:true
输入:s = "()[]{}"
输出:true
输入:s = "(]"
输出:false
输入:s = "([)]"
输出:false
输入:s = "{[]}"
输出:true
- 1 <= s.length <= 104
- s 仅由括号 '()[]{}' 组成
二丶思路分析
使用栈来解决先进后出- 当遇到左括号时候,入栈
- 当遇到右括号时候,取出栈顶括号
- 判断出去括号 是否跟右括号类型一致,不一致,直接返回
false
- 如果栈中没有左括号了,也直接返回
false
- 当遍历完所有的字符串
- 栈为空,说明所有的括号都闭合了
- 栈不为空,说明还有括号没有匹配闭合
- 当匹配的时候,字符串长度一定为偶数,否则肯定不匹配,直接返回
false
- 为了方便匹配,我们可以用哈希表存储每一种括号。键为右括号,值为相同类型的左括号。
三、代码实现
class Solution {
public boolean isValid(String s) {
int length = s.length();
if (length % 2 != 0) {
return false;
}
Map<Character, Character> map = new HashMap<Character, Character>() {{
put(')', '(');
put(']', '[');
put('}', '{');
}};
Deque<Character> stack = new LinkedList<Character>();
for (int i = 0; i < length; i++) {
char ch = s.charAt(i);
if (map.containsKey(ch)) {
if (stack.isEmpty() || stack.peek() != map.get(ch)) {
return false;
}
stack.pop();
} else {
stack.push(ch);
}
}
return stack.isEmpty();
}
}
复杂度分析
ns运行结果

总结
边栏推荐
- Growth of operation and maintenance Xiaobai - week 8 of Architecture
- 单细胞代码解析-妇科癌症单细胞转录组及染色质可及性分析1
- 0629 ~ SaaS platform design ~ global exception handling
- 0625~<config>-<bus>
- 0630~ professional quality course
- 模拟实现vector
- 继承与派生
- Three ways of redis cluster
- 去不图床容量兑换
- Wu Enda writes: how to establish projects to adapt to AI career
猜你喜欢

Mozilla foundation released 2022 Internet health report: AI will contribute 15.7 trillion yuan to the global economy in 2030, and the investment in AI in the United States last year was nearly three t

0625~<config>-<bus>

下拉列表组件使用 iScroll.js 实现滚动效果遇到的坑

web渗透经验汇总ing

0625~<config>-<bus>

Inherit, override, overload

Use prometheus+grafana to monitor MySQL performance indicators

05mysql lock analysis

How does win11 enhance the microphone? Win11 enhanced microphone settings
![[leetcode] 30. Concatenate substrings of all words](/img/21/3965532a31553cfe6edf64ca5de3f4.png)
[leetcode] 30. Concatenate substrings of all words
随机推荐
[network security] analysis vulnerability of website Middleware
深入解析著名的阿里云Log4j 漏洞
Interview assault 66: what is the difference between request forwarding and request redirection?
《STL源码剖析》应该怎样读?
0625~<config>-<bus>
Laravel notes - RSA encryption of user login password (improve system security)
Alibaba /1688 API instructions for searching products by map (pailitao)
仅需一个依赖给Swagger换上新皮肤,既简单又炫酷!
还在从零开始搭建项目?这款升级版快速开发脚手架值得一试!
0614~放假自习
PXE高效批量网络装机
Section 11 cache avalanche, hot data failure follow Daewoo redis ------- directory post
Use of jumpserver
Section 10 cache breakdown follow Daewoo redis ------- directory post
头文件是必须的吗?跟一跟编译过程~~~
使用Prometheus+Grafana监控MySQL性能指标
Simple test JS code
(mandatory) override equals must override hashcode (principle analysis)
0627~放假知识总结
Go language file operation