#include <bits/stdc++.h>
using namespace std ;
const int MAX = 1e5 + 10 ;
int arr[MAX] ;
int n ;
string s ;
stack<char>st ;
int prv[MAX][26] ;
char ans[MAX] ;
void solve(int l , int r)
{
if(l > r)
return ;
int idx = prv[r][s[l]-'a'] ;
ans[l] = '(' , ans[idx] = ')' ;
solve(l+1 , idx-1) , solve(idx+1 , r) ;
}
int main()
{
ios_base::sync_with_stdio(0) ;
cin.tie(0) ;
cin>>s ;
n = s.size() ;
s = '#' + s ;
for(int i = 1 ; i <= n ; ++i)
{
if(st.size() && st.top() == s[i])
st.pop() ;
else
st.push(s[i]) ;
}
if(st.size())
return cout<<-1<<"\n" , 0 ;
for(int i = 1 ; i <= n ; ++i)
{
int x = prv[i-1][(s[i] - 'a')] ;
for(int j = 0 ; j < 26 ; ++j)
{
if((s[i] - 'a') == j)
prv[i][j] = i ;
else if(x)
prv[i][j] = prv[x-1][j] ;
}
}
solve(1 , n) ;
for(int i = 1 ; i <= n ; ++i)
cout<<ans[i] ;
cout<<"\n" ;
return 0 ;
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
0 ms |
332 KB |
Output is correct |
2 |
Correct |
0 ms |
332 KB |
Output is correct |
3 |
Correct |
0 ms |
332 KB |
Output is correct |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
0 ms |
332 KB |
Output is correct |
2 |
Correct |
0 ms |
332 KB |
Output is correct |
3 |
Correct |
0 ms |
332 KB |
Output is correct |
4 |
Correct |
1 ms |
332 KB |
Output is correct |
5 |
Correct |
1 ms |
332 KB |
Output is correct |
6 |
Correct |
1 ms |
460 KB |
Output is correct |
7 |
Correct |
1 ms |
460 KB |
Output is correct |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
0 ms |
332 KB |
Output is correct |
2 |
Correct |
0 ms |
332 KB |
Output is correct |
3 |
Correct |
0 ms |
332 KB |
Output is correct |
4 |
Correct |
1 ms |
332 KB |
Output is correct |
5 |
Correct |
1 ms |
332 KB |
Output is correct |
6 |
Correct |
1 ms |
460 KB |
Output is correct |
7 |
Correct |
1 ms |
460 KB |
Output is correct |
8 |
Correct |
1 ms |
972 KB |
Output is correct |
9 |
Correct |
1 ms |
1100 KB |
Output is correct |
10 |
Correct |
1 ms |
1100 KB |
Output is correct |
11 |
Correct |
1 ms |
1228 KB |
Output is correct |
12 |
Correct |
8 ms |
7756 KB |
Output is correct |
13 |
Correct |
10 ms |
8396 KB |
Output is correct |
14 |
Correct |
10 ms |
9148 KB |
Output is correct |
15 |
Correct |
12 ms |
10884 KB |
Output is correct |
16 |
Correct |
14 ms |
10816 KB |
Output is correct |
17 |
Correct |
12 ms |
11344 KB |
Output is correct |
18 |
Correct |
17 ms |
10708 KB |
Output is correct |
19 |
Correct |
14 ms |
11592 KB |
Output is correct |
20 |
Correct |
8 ms |
8012 KB |
Output is correct |
21 |
Correct |
16 ms |
12516 KB |
Output is correct |