[LeetCode] Valid Parentheses

This is a classic problem of the application of stacks. The idea is, each time we meet a ({ or[, we push it to a stack. If we meet a )} or ], we check if the stack is not empty and the top matches it. If not, return false; otherwise, we pop the stack. Finally, if the stack is empty, returntrue; otherwise, return false.

The code is as follows, very straight-forward.

复制代码
 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         stack<char> paren;
 5         for (int i = 0; i < s.length(); i++) {
 6             if (s[i] == '(' || s[i] == '{' || s[i] == '[')
 7                 paren.push(s[i]);
 8             else if (s[i] == ')' || s[i] == '}' || s[i] == ']') {
 9                 if (paren.empty()) return false;
10                 if (!match(paren.top(), s[i])) return false;
11                 paren.pop();
12             }
13         }
14         return paren.empty();
15     }
16 private:
17     bool match(char s, char t) {
18         if (t == ')') return s == '(';
19         if (t == '}') return s == '{';
20         if (t == ']') return s == '[';
21     }
22 };
复制代码

 

posted @   jianchao-li  阅读(203)  评论(0)    收藏  举报
编辑推荐:
· 长文讲解 MCP 和案例实战
· Hangfire Redis 实现秒级定时任务,使用 CQRS 实现动态执行代码
· Android编译时动态插入代码原理与实践
· 解锁.NET 9性能优化黑科技:从内存管理到Web性能的最全指南
· 通过一个DEMO理解MCP(模型上下文协议)的生命周期
阅读排行:
· 工良出品 | 长文讲解 MCP 和案例实战
· 一天 Star 破万的开源项目「GitHub 热点速览」
· 多年后再做Web开发,AI帮大忙
· 记一次 .NET某旅行社酒店管理系统 卡死分析
· 别再堆文档了,大模型时代知识库应该这样建
点击右上角即可分享
微信分享提示