leetcode Valid Parentheses

本文介绍了一种使用堆栈解决括号匹配问题的有效方法。通过一个具体的C++实现案例,展示了如何判断字符串中的括号是否正确配对。利用堆栈特性,实现了括号的匹配检查,并确保所有类型的括号(圆括号、方括号和花括号)都按正确的顺序闭合。

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

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.

 

Subscribe to see which companies asked this question

 

这个题我应该是见过的,但是具体在哪儿见过我不记得了。

刚开始想的比较简单,也打算用循环来做,发现这样很容易某个情况没有考虑到。陷入僵局。

后来猛然想起来——堆栈!

堆栈很适合这种匹配类问题啊,如果匹配了就出栈,如果没有匹配就压栈,等待匹配,最后看堆栈是否为空就行了。

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         int length=s.length(),i=1,temp=0;
 5         if(length%2!=0||length==0) return false;
 6         map<int,int> dic;
 7         dic[40]=41;
 8         dic[91]=93;
 9         dic[123]=125;
10         stack<char> match;
11         match.push(s[0]);
12         while(!match.empty()&&i<length){
13             temp=match.top();
14             if(dic.find(temp)==dic.end()) return false;
15             if(s[i]==dic[temp]){i++; match.pop();}
16             else match.push(s[i++]);
17         }
18         if(match.empty()) return true;
19         else return false;
20         
21     }
22 };

 

转载于:https://www.cnblogs.com/LUO77/p/5047560.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值