Leetcode 2696. Minimum String Length After Removing Substrings
Given a string s
, you are tasked with removing instances of substrings “AB” and “CD” from the string as many times as possible until it’s not possible to remove any more substrings. Your final goal is to return the minimum possible length of the resulting string.
s
contain?
s
will only consist of uppercase English letters.s
?
Here is the solution to the problem:
public class Solution {
public int minLength(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (!stack.isEmpty() && ((stack.peek() == 'A' && c == 'B') || (stack.peek() == 'C' && c == 'D'))) {
stack.pop(); // Remove the matching 'A' or 'C'
} else {
stack.push(c); // Push the current character onto the stack
}
}
// The size of the stack is the minimum length of the string
return stack.size();
}
}
n
is the length of the string. Each character is processed exactly once, either pushed onto the stack or then popped.This approach ensures that we efficiently reduce the string length by treating removal of substrings through a stack structure, which provides a clean and simple O(n) solution.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?