Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5a7f106

Browse files
solves #2696: Minimum string length after removing substrings
1 parent 080b52d commit 5a7f106

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /