-
Notifications
You must be signed in to change notification settings - Fork 0
/
LC2696.java
50 lines (40 loc) · 1.18 KB
/
LC2696.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
// problem: 2696. Minimum String Length After Removing Substrings
// difficulty: easy
// runtime: 4-5ms, beats 84%
class Solution {
public int minLength(String s) {
if (s.length() == 1) return 1;
Stack<Character> stack = new Stack<>();
int count = 0;
for (char c : s.toCharArray()) {
if (stack.empty()) {
stack.push(c);
continue;
}
if (c == 'B' && stack.peek() == 'A') {
stack.pop();
continue;
}
if (c == 'D' && stack.peek() == 'C') {
stack.pop();
continue;
} else stack.push(c);
}
return stack.size();
}
}
class Solution {
public int minLength(String s) {
if (s.length() == 1) return 1;
Stack<Character> stack = new Stack<>();
char temp = ' ';
for (char c : s.toCharArray()) {
if (!stack.empty()) temp = stack.peek();
else temp = ' ';
if (c == 'B' && temp == 'A' || c == 'D' && temp == 'C') {
stack.pop();
} else stack.push(c);
}
return stack.size();
}
}