-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMinimumAddToMakeParenthesesValid921.kt
47 lines (41 loc) · 1.3 KB
/
MinimumAddToMakeParenthesesValid921.kt
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
package medium
import java.util.Stack
object MinimumAddToMakeParenthesesValid921 {
fun minAddToMakeValid(s: String): Int {
val stack = Stack<Char>()
s.forEach { char ->
if (char == '(' || stack.isEmpty())
stack.push(char)
else {
if (stack.isNotEmpty()) {
val peek = stack.peek()
if (peek == '(')
stack.pop()
else
stack.push(char)
}
}
}
return stack.size
}
fun minAddToMakeValidSolution2(s: String): Int {
// initialize openBrackets to track unmatched open brackets
var openBrackets = 0
var minAddRequired = 0
s.forEach { char ->
if (char == '(')
openBrackets++
else {
// If an open bracket exists, match it with the closing one
// If not, we need to add an open bracket
if (openBrackets > 0) {
openBrackets--
} else {
minAddRequired++
}
}
}
// Add the remaining open brackets as closing brackets would be required
return minAddRequired + openBrackets
}
}