题目链接
思路:
先将正常的括号入栈,如果左括号少,那就将最前面的星号边成左括号,如果最后还有多余的左括号,那就将最后面的星号变成右括号。
代码:
#include<bits/stdc++.h>
#define int long long
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
const int N=2e5+5;
const int M=2e4+5;
const double eps=1e-8;
const int mod=1e9+7;
const int inf=0x7fffffff;
const double pi=3.1415926;
using namespace std;
char s[N];
stack<int>stk;
deque<int>q;
signed main()
{
int t;
cin>>t;
while(t--)
{
while(!stk.empty())
{
stk.pop();
}
while(!q.empty())
{
q.pop_back();
}
cin>>s+1;
int n=strlen(s + 1),flag=1;
for(int i=1;i<=n;i++)
{
if(s[i]=='*')
{
q.push_back(i);
}
if(s[i]==')')
{
if(!stk.empty())
{
stk.pop();
}
else if(!q.empty())
{
s[q.front()] = '(';
q.pop_front();
}
else
{
flag = 0;
break;
}
}
if(s[i]=='(')
{
stk.push(i);
}
}
while(!stk.empty())
{
if(!q.empty()&&q.back()>stk.top())
{
s[q.back()]=')';
stk.pop();
q.pop_back();
}
else
{
flag = 0;
break;
}
}
if(flag == 0)
{
cout<<"No solution!"<<endl;
}
else
{
for(int i=1;i<=n;i++)
{
if(s[i]=='('||s[i]==')')
{
cout<<s[i];
}
}
cout<<endl;
}
}
return 0;
}