-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMinimumStringLengthAfterRemovingSubstrings2696.kt
More file actions
42 lines (35 loc) · 1.17 KB
/
MinimumStringLengthAfterRemovingSubstrings2696.kt
File metadata and controls
42 lines (35 loc) · 1.17 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
package easy
import java.util.Stack
object MinimumStringLengthAfterRemovingSubstrings2696 {
fun minLength(s: String): Int {
val characterStack = Stack<Char>()
s.forEach { char ->
if (char == 'B' && characterStack.isNotEmpty() && characterStack.peek() == 'A') {
characterStack.pop()
} else if (char == 'D' && characterStack.isNotEmpty() && characterStack.peek() == 'C') {
characterStack.pop()
} else
characterStack.push(char)
}
return characterStack.size
}
/**
* String Replace
*/
fun minLengthSolution2(s: String): Int {
var string = s
// Continue processing while "AB" or "CD" substrings exist
while (string.contains("AB") || string.contains("CD")) {
if (string.contains("AB"))
{
// Remove the occurrences of "AB"
string = string.replace("AB","")
}else if(string.contains("CD"))
{
// Remove the occurrences of "CD"
string = string.replace("CD","")
}
}
return string.length
}
}