Sponsored
Sponsored
This approach involves using a stack data structure to handle the character removals efficiently.
Iterate through each character in the string s
. Use the stack to maintain a record of the characters processed so far. For each new character, compare it with the character at the top of the stack. If they form a bad pair (for example, if one is a lower-case and the other is the same letter in upper-case), pop the stack. Otherwise, push the current character onto the stack.
The stack will ensure that all bad pairs are removed as you process the string, and the remaining elements in the stack will form the good string.
Time Complexity: O(n), where n is the length of the string. We make a single pass through the string.
Space Complexity: O(n), because we may store all characters of the string in the worst case (if no removals are made).
1function makeGood(s) {
2 const stack = [];
3 for (let c of s) {
4 if (stack.
In JavaScript, an array functions as the stack. The array helper methods push()
and pop()
are used to manipulate the stack as characters are processed, efficiently constructing a good string in one pass.
The two-pointer technique allows us to traverse the string using two indices to find and remove bad pairs directly. This could potentially minimize contiguous sections of bad pairs before further adjusting the string.
By initially placing one pointer at the start and the other incrementing through the string, check adjacent pairs for bad sequences directly, shifting strings as necessary, allowing further analysis.
While effectively a simulation of stack behavior, avoiding using additional storage structures explicitly, this approach may involve more complex logic to ensure the traversal maintains correct indices.
Time Complexity: O(n), iterating through input once.
Space Complexity: O(1) and no auxiliary data structures are used.
#include <string>
using namespace std;
string makeGood(string s) {
int i = 0;
for (int j = 0; j < s.length(); j++) {
if (i > 0 && (s[i - 1] == s[j] + 32 || s[i - 1] == s[j] - 32)) {
i--;
} else {
s[i++] = s[j];
}
}
return s.substr(0, i);
}
int main() {
string s = "leEeetcode";
cout << makeGood(s) << endl;
return 0;
}
Using C++, we minimize memory alterations by controlling index evolution and directly editing to assemble the resultant string. Mathematical pointer management ensures valid sequence adjustments without additional storage.