Make The String Great
Easy
Topics
A good string has no two adjacent characters where one is the lowercase and the other the uppercase of the same letter. Repeatedly remove such pairs from s and return the result.
Example 1
leetcode.Input: s = "leEeetcode" Output: "leetcode"
Example 2
Input: s = "abBAcC" Output: ""
Constraints
- 1 <= s.length <= 100
- s contains upper and lower case English letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
A "bad" pair is two adjacent characters that are the same letter in opposite cases, and removing one can create a new adjacency that is also bad — "abBA" removes bB, which brings a and A together, and those must go too. Repeatedly rescanning the string is correct but O(n^2).
A stack handles the cascade in one pass. Push characters as they come; before pushing, check whether the incoming character annihilates the current top. If it does, pop instead of pushing, and the next character is then compared against the new top — which is exactly the cascade, handled for free.
The test for a bad pair is "same letter, different case": top != c but top.lower() == c.lower(). Both halves are needed — the first rules out "aa", which is perfectly fine.
Approach
- For each character, if the stack is non-empty and the top forms a bad pair with it, pop; otherwise push.
- Join what remains.
Dry Run
s = "abBAcC"
a stack empty -> push [a]
b top 'a', different letter [a,b]
B top 'b', same letter opposite case -> pop [a]
A top 'a', same letter opposite case -> pop []
c stack empty -> push [c]
C top 'c', bad pair -> pop []
answer ""
note the cascade: removing bB is what made aA adjacent,
and the stack caught it without a second passComplexity
- Time — O(n): each character is pushed at most once and popped at most once. Against O(n^2) for rescanning after every removal.
- Space — O(n): the stack, which holds the whole string when nothing cancels.
Common Pitfalls
- Omitting the
top != chalf of the test, which would delete"aa"— a legal pair that must survive. - Comparing with a case-insensitive equality only, which has the same effect.
- Rescanning from the start after each removal. Correct but quadratic; the stack is what makes it linear.
- Using
abs(ord(a) - ord(b)) == 32as the test. It works for ASCII letters and is the kind of trick that silently breaks on other input; the case comparison says what is meant. - Popping without checking the stack is non-empty.
Full Solution — all languages
class Solution:
def makeGood(self, s):
stack = []
for c in s:
if stack and stack[-1] != c and stack[-1].lower() == c.lower():
stack.pop()
else:
stack.append(c)
return "".join(stack)import java.util.*;
class Solution {
public String makeGood(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (sb.length() > 0) {
char t = sb.charAt(sb.length() - 1);
if (t != c && Character.toLowerCase(t) == Character.toLowerCase(c)) {
sb.deleteCharAt(sb.length() - 1);
continue;
}
}
sb.append(c);
}
return sb.toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string makeGood(string s) {
string stack;
for (char c : s) {
if (!stack.empty() && stack.back() != c && tolower(stack.back()) == tolower(c)) stack.pop_back();
else stack.push_back(c);
}
return stack;
}
};/**
* @param {string} s
* @return {string}
*/ var makeGood = function(s) {
const stack = [];
for (const c of s) {
if (stack.length && stack[stack.length - 1] !== c && stack[stack.length - 1].toLowerCase() === c.toLowerCase()) stack.pop();
else stack.push(c);
}
return stack.join('');
};