-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimumBracketReversal.java
More file actions
53 lines (48 loc) · 1.21 KB
/
MinimumBracketReversal.java
File metadata and controls
53 lines (48 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.util.Stack;
public class Solution {
public static int countBracketReversals(String input) {
if(input.length()%2==1)
{
return -1;
}
Stack<Character> s = new Stack<>();
int count = 0;
for(int i =0;i<input.length();i++)
{
if(input.charAt(i)!='}')
{
s.push(input.charAt(i));
}
else if(input.charAt(i)=='}' && (s.isEmpty()==true || s.peek()=='}'))
{
s.push(input.charAt(i));
}
else if(input.charAt(i)=='}' && (s.peek()=='{' && s.isEmpty()!=true))
{
s.pop();
}
else if(input.charAt(i)=='}')
{
s.push(input.charAt(i));
}
}
// while(!s.isEmpty())
// {
// System.out.print(s.pop()+" ");
// }
while(!s.isEmpty())
{
char c1 = s.pop();
char c2 = s.pop();
if(c1==c2)
{
count++;
}
else if(c1=='{' && c2=='}')
{
count+=2;
}
}
return count;
}
}