Sponsored
Sponsored
This approach revolves around using a stack to efficiently identify and remove the substrings "AB" and "CD" from the given string. By traversing each character of the string:
The characters that remain on the stack are the ones that could not form any removable patterns, thus forming the result string.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), to store the stack elements, based on the worst case where no pairs are removed.
1#include <iostream>
2#include <stack>
3using namespace std;
4
5int minLengthAfterRemovals(string s) {
6 stack<char> st;
7 for (char c : s) {
8 if (!st.empty() && ((c == 'B' && st.top() == 'A') || (c == 'D' && st.top() == 'C'))) {
9 st.pop();
10 } else {
11 st.push(c);
12 }
13 }
14 return st.size();
}
int main() {
string s = "ABFCACDB";
cout << minLengthAfterRemovals(s) << endl;
return 0;
}
This C++ solution uses the standard stack
from the STL to manage the stack operations. We iterate through the string and apply push/pop operations based on matching conditions.
This technique uses a two-pointer approach to reduce the string by altering it in place. The core idea is to selectively overwrite positions in the string:
After reaching the end of the string, the length of the string from the start to the write pointer represents the reduced string length.
Time Complexity: O(n), dependent on examining each character once.
Space Complexity: O(1), as no additional data structures are used.
1function minLengthAfterRemovals(s) {
2 let arr = s.split(''); // Convert string to array for direct manipulation
3 let write = 0;
4 for (let read = 0; read < arr.length; read++) {
5 if (write > 0 && ((arr[read] === 'B' && arr[write - 1] === 'A') || (arr[read] === 'D' && arr[write - 1] === 'C'))) {
6 write--;
7 } else {
8 arr[write++] = arr[read];
9 }
10 }
11 return write;
12}
13
14const s = "ABFCACDB";
15console.log(minLengthAfterRemovals(s));
JavaScript's string-to-array conversion allows us to directly alter the sequence with a write pointer to evaluate and bypass pairs.