File tree 1 file changed +31
-0
lines changed
1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ // https://leetcode.com/problems/minimum-string-length-after-removing-substrings
2
+ // T: O(N)
3
+ // S: O(N)
4
+
5
+ import java .util .Set ;
6
+ import java .util .Stack ;
7
+
8
+ public class MinimumStringLengthAfterRemovingSubstrings {
9
+ final static Set <Character > REMOVAL_TERMINATING_CHARS = Set .of ('B' , 'D' );
10
+
11
+ public int minLength (String s ) {
12
+ final Stack <Character > stack = new Stack <>();
13
+ for (int i = 0 ; i < s .length () ; i ++) {
14
+ final char letter = s .charAt (i );
15
+ if (!stack .isEmpty () && REMOVAL_TERMINATING_CHARS .contains (letter ) && stack .peek () == inverse (letter )) {
16
+ stack .pop ();
17
+ } else {
18
+ stack .push (letter );
19
+ }
20
+ }
21
+ return stack .size ();
22
+ }
23
+
24
+ private char inverse (char letter ) {
25
+ return switch (letter ) {
26
+ case 'B' -> 'A' ;
27
+ case 'D' -> 'C' ;
28
+ default -> ' ' ;
29
+ };
30
+ }
31
+ }
You can’t perform that action at this time.
0 commit comments