Leetcode 20. Valid Parentheses

本文介绍了一种使用栈数据结构和哈希表来验证括号字符串是否有效的算法。该算法适用于仅包含'(',')','{','}

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

20. Valid Parentheses

  • Total Accepted: 128586
  • Total Submissions: 418560
  • Difficulty: Easy

 

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

 

思路:利用栈来判断配对的括号,如果都可以配对成功,最后栈的元素数量应该为0。题目给定的字符串只包含括号,所以每次遇到是(', '{'或者'[',直接入栈;遇到']',')'或者']',只有当栈不为空&&栈顶元素与之配对时,才弹出栈,否则直接返回false。

 

代码:

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         stack<char> cs;
 5         unordered_map<char, char> um;
 6         um['('] = ')';
 7         um['{'] = '}';
 8         um['['] = ']';
 9         for (int i = 0; i < s.size(); i++) {
10             if (s[i] == '(' || s[i] == '{' || s[i] == '[') {
11                 cs.push(s[i]);
12                 continue;
13             }
14             if (!cs.empty() && um[cs.top()] == s[i]){
15                 cs.pop();
16                 continue;
17             } 
18             return false;
19         }
20         return cs.empty();
21     }
22 };

 

转载于:https://www.cnblogs.com/Deribs4/p/5838714.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值