LC.P2696[删除子串后的字符串最小长度]

方法一:栈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int minLength(String s) {
Deque<Character> stack = new ArrayDeque<>();
stack.push(' ');
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if ((c == 'B' && stack.peek() == 'A') || (c == 'D' && stack.peek() == 'C')) {
stack.pop();
} else {
stack.push(c);
}
}
return stack.size() - 1;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$