Skip to content

Commit 989fa8f

Browse files
authored
Update Minimum Bracket Reversal
1 parent 9f2bd82 commit 989fa8f

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Course 2 - Data Structures in JAVA/Lecture 9 - Stacks/Minimum Bracket Reversal

+54
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,57 @@ Sample Input 2:
3131
Sample Output 2:
3232
1
3333
*/
34+
import java.util.*;
35+
public class Solution {
36+
37+
public static int countBracketReversals(String input) {
38+
//Your code goes here
39+
if (input.length()%2!=0)
40+
{
41+
return -1;
42+
}
43+
Stack<Character> stack=new Stack<Character>();
44+
int count=0;
45+
for (int i=0;i<input.length();i++)
46+
{
47+
char c=input.charAt(i);
48+
if (c=='{')
49+
{
50+
stack.push(c);
51+
}
52+
else
53+
{
54+
if (stack.isEmpty())
55+
{
56+
stack.push(c);
57+
}
58+
else if (stack.peek()=='}')
59+
{
60+
stack.push(c);
61+
}
62+
else if (stack.peek()=='{')
63+
{
64+
stack.pop();
65+
}
66+
}
67+
}
68+
69+
while(!stack.isEmpty())
70+
{
71+
char c1=stack.pop();
72+
char c2=stack.pop();
73+
74+
if (c1==c2)
75+
{
76+
count=count+1;
77+
}
78+
else
79+
{
80+
count=count+2;
81+
}
82+
}
83+
return count;
84+
85+
}
86+
87+
}

0 commit comments

Comments
 (0)