Problem Statement:
Given a string S consisting only of opening and closing curly brackets '{' and '}' find out the minimum number of reversals required to make a balanced expression.
Input
The first line of input contains an integer T denoting the number of test cases. Then T test cases
follow.
The first line of each test case contains a string S consisting only of { and }.
The first line of input contains an integer T denoting the number of test cases. Then T test cases
follow.
The first line of each test case contains a string S consisting only of { and }.
Output
Print out minimum reversals required to make S balanced.If it cannot be balanced, then print -1.
Constraints
1 <= T <= 100
0 < S <= 50
Examples
Input
4
}{{}}{{{
{{}}}}
{{}{{{}{{}}{{
{{{{}}}}
4
}{{}}{{{
{{}}}}
{{}{{{}{{}}{{
{{{{}}}}
Output
3
1
-1
0
3
1
-1
0
Expected Complexity
Time: O(n)
Space: O(n)
Time: O(n)
Space: O(n)
Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int i=0;i<t;i++)
{
int count=0;
String s=sc.next();
Stack <Character>h=new Stack<Character>();
int flag=0;
if(s.length()%2!=0)
{
flag=1;
}
else {
for(int j=0;j<s.length();j++)
{
char ch=s.charAt(j);
if(ch=='{')
{
h.push(ch);
}
else if(ch=='}')
{
if(!h.empty() && h.peek()=='{')
{
h.pop();
}
else{
h.push(ch);
}
}
}
while(!h.empty())
{
char x=h.pop();
if(x=='{')
{
if(!h.empty() && h.peek()=='{')
{
count=count+1;
h.pop();
}
else if(!h.empty() && h.peek()=='}')
{
count=count+2;
h.pop();
}
else {
flag=1;
}
}
else if(x=='}')
{
if(!h.empty() && h.peek()=='}')
{
count=count+1;
h.pop();
}
else if(!h.empty() && h.peek()=='{')
{
h.pop();
}
else {
flag=1;
}
}
}
}
if(flag==0){
System.out.println(count);
}
else{
System.out.println("-1");
}
}
}
}
Comments
Post a Comment