-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinimizeLength.java
96 lines (74 loc) · 2.13 KB
/
MinimizeLength.java
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package Stack;
public class MinimizeLength {
public static void deleteSubseq(String s)
{
// Length of the string
int N = s.length();
// Stores opening parenthesis
// '(' of the given string
Stack<Character> roundStk = new Stack<>();
// Stores square parenthesis
// '[' of the given string
Stack<Character> squareStk = new Stack<>();
// Stores count of opening parenthesis '('
// in valid subsequences
int roundCount = 0;
// Stores count of opening parenthesis '['
// in valid subsequences
int squareCount = 0;
// Iterate over each
// characters of S
for (int i = 0; i < N; i++)
{
// If current character is '['
if (s.charAt(i) == '[')
{
// insert into stack
squareStk.push(s.charAt(i));
}
// If i is equal to ']'
else if (s.charAt(i) == ']')
{
// If stack is not empty and
// top element of stack is '['
if (squareStk.size() != 0
&& squareStk.peek() == '[')
{
// Remove top element from stack
squareStk.pop();
// Update squareCount
squareCount += 1;
}
}
// If current character is '('
else if (s.charAt(i) == '(')
{
// Insert into stack
roundStk.push(s.charAt(i));
}
// If i is equal to ')'
else
{
// If stack is not empty and
// top element of stack is '('
if (roundStk.size() != 0
&& squareStk.peek() == '(')
{
// Remove top element from stack
squareStk.pop();
// Update roundCount
roundCount += 1;
}
}
}
// Print the minimum number of remaining
// characters left into S
System.out.println(
N - (2 * squareCount + 2 * roundCount));
}
public static void main(String[] args) {
String s = "[]])([";
// function call
deleteSubseq(s);
}
}