P1241 括号序列
RE一半
#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;
}
标签:P1241,cnt,ch,sta,vis,char,括号,序列,include
From: https://www.cnblogs.com/kdlyh/p/17846617.html