leetcode Valid Parentheses

本文介绍了一个使用 C++ 实现的括号匹配验证算法。通过 map 和 stack 数据结构,该算法可以判断字符串中的括号是否正确配对。主要内容包括:1) 使用 map 存储括号的对应关系;2) 利用 stack 进行括号匹配检查。

代码:

 1 #include<iostream>
 2 #include<stack>
 3 #include<map>
 4 
 5 using namespace std;
 6 
 7 bool isValid(string s) {
 8     map<char, char> smap;
 9     smap.insert(make_pair('(', ')'));
10     smap.insert(make_pair('[', ']'));
11     smap.insert(make_pair('{', '}'));
12     stack<char> ss;
13     int i=0;
14     int L = s.length();
15     while (i<L)
16     {
17         char c = s[i];
18         if (!ss.empty()&&c==smap[ss.top()])
19         {
20             ss.pop();
21         }
22         else
23         {
24             ss.push(c);
25         }
26         i++;
27     }
28     if (ss.empty())
29     {
30         return true;
31     }
32     else
33         return false;
34 }
35 
36 int main()
37 {
38     cout << isValid("()[()]") << endl;
39 }

 

转载于:https://www.cnblogs.com/chaiwentao/p/4427818.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值