Leetcode 1544. Make The String Great
The problem is defined as follows:
Given a string s
of lower and upper case English letters, a good string is a string where no two adjacent characters are the same letter with different cases.
For example, “leEeetcode” is not good because ‘e’ and ‘E’ are adjacent to each other, but “leetcode” and “leEeetcode” is not good because ‘e’ and ‘E’ are adjacent to each other. However, “leetcode” is a good string because it does not have two adjacent characters that are the same letter with different cases.
To make the string good, you can choose two adjacent characters that make the string not good and remove them. You can keep doing this until the string becomes good.
Return the string after making it good. The answer is guaranteed to be unique under the given constraints.
Input: s = "leEeetcode"
Output: "leetcode"
A feasible strategy for this problem is to use a stack to handle the removals of problematic adjacent characters. The key idea is to iterate through the string:
Here’s the C++ solution for the problem:
#include <iostream>
#include <stack>
#include <string>
#include <cctype>
using namespace std;
string makeGood(string s) {
// Use a stack to help in removing bad adjacent pairs
stack<char> st;
for (char ch : s) {
if (!st.empty() && abs(st.top() - ch) == 32) { // 32 is the difference between lowercase and uppercase alphabet
st.pop();
} else {
st.push(ch);
}
}
// Construct the resulting string from the stack
string result = "";
while (!st.empty()) {
result = st.top() + result;
st.pop();
}
return result;
}
// Test code
int main() {
string s = "leEeetcode";
cout << "Output: " << makeGood(s) << endl; // Output should be "leetcode"
return 0;
}
O(n)
, where n
is the length of the string.O(n)
in the worst case.Therefore, the overall time complexity is O(n), which is efficient for this problem.
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?