P1241 括号序列

1|0P1241 括号序列

1|1RE一半

#include<iostream> #include<algorithm> #include<cstdio> #include<stack> using namespace std; string s; char ans[400]; bool vis[400]; int cnt = 0; stack<pair<int, char>> sta; bool check(char ch1, char ch2) { return (ch1 == '(' && ch2 == ')') || (ch1 == '[' && ch2 == ']'); } void print(char a) { if (a == '[' || a == ']') { cout << "[]"; } if (a == ')' || a == '(') { cout << "()"; } } int main() { cin >> s; for (auto ch : s) { ans[++cnt] = ch; if (ch == '[' || ch == '(') sta.push({cnt,ch}); else if (check(sta.top().second, ch)) { vis[cnt] = true; vis[sta.top().first] = true; sta.pop(); } } for (int i = 1; i <= cnt; i++) { if(!vis[i]) { print(ans[i]); } else { cout<<ans[i]; } } return 0; }

问题在于有时候可能栈是空的,这时再执行调取栈顶和出栈等操作就会导致运行时错误。

特判即可。

#include<iostream> #include<algorithm> #include<cstdio> #include<stack> using namespace std; string s; char ans[400]; bool vis[400]; int cnt = 0; stack<pair<int, char>> sta; bool check(char ch1, char ch2) { return (ch1 == '(' && ch2 == ')') || (ch1 == '[' && ch2 == ']'); } void print(char a) { if (a == '[' || a == ']') { cout << "[]"; } if (a == ')' || a == '(') { cout << "()"; } } int main() { cin >> s; for (auto ch : s) { ans[++cnt] = ch; if (ch == '[' || ch == '(') { sta.push({cnt,ch}); continue; } if (sta.empty()) { continue; } if (check(sta.top().second, ch)) { vis[cnt] = true; vis[sta.top().first] = true; sta.pop(); } } for (int i = 1; i <= cnt; i++) { if(!vis[i]) { print(ans[i]); } else { cout<<ans[i]; } } return 0; }

__EOF__

本文作者Kdlyh
本文链接https://www.cnblogs.com/kdlyh/p/17846617.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   加固文明幻景  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示