NYOJ--2--括号配对问题

本文介绍了两种解决括号匹配问题的有效算法。一种是利用栈结构进行实时匹配验证,另一种则是通过字符串替换逐步消除已匹配括号对的方法。两种算法各有优劣,前者直观且易于实现,后者则更简洁高效。

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

 1 /*
 2     Name: NYOJ--2--括号配对问题
 3     Author: shen_渊 
 4     Date: 18/04/17 21:15
 5     Description: 先入栈个‘#’ 就好做了 
 6 */
 7 #include<bits/stdc++.h> 
 8 using namespace std;
 9 bool cmp(char,char) ;
10 int main(){
11     int n;cin>>n;
12     while(n--){
13         string str;cin>>str;
14         stack<char> s;
15         while(!s.empty())s.pop();
16         s.push('#');//
17         for(int i=0; i<str.size(); ++i){
18             if(str[i]=='[' || str[i]=='(')
19                     s.push(str[i]);
20                 else if((str[i]==']' &&s.top()=='[') || (str[i]==')' && s.top()=='('))
21                     s.pop();
22                 else
23                     s.push(str[i]);
24         }
25         if(s.top() != '#')cout<<"No"<<endl;
26         else cout<<"Yes"<<endl;
27         while(s.top() != '#')s.pop();
28     }
29     return 0;
30 }
31 bool cmp(char c,char cc){
32     if(c == '(' && cc == ')')return 1;
33     else if(c == '[' && cc == ']')return 1;
34     else return 0;
35 }
36 /*
37     仔细一想,于是…… 
38 */
39 #include<bits/stdc++.h> 
40 using namespace std;
41 bool cmp(char,char) ;
42 int main(){
43     int n;cin>>n;
44     while(n--){
45         string str;cin>>str;
46         int a = 0,b = -1,pos; 
47         while(a != b){
48             a = str.size();
49             while((pos = str.find("()")) != string::npos)str.erase(pos,2);
50             while((pos = str.find("[]")) != string::npos)str.erase(pos,2);
51             b = str.size();
52         } 
53         if(str == "")cout<<"Yes"<<endl;
54         else cout<<"No"<<endl;
55     }
56     return 0;
57 }

 

转载于:https://www.cnblogs.com/evidd/p/7251867.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值