LeetCode Problem 1544: Make The String Great
Description:
Given a string s
of lower and upper case English letters.
A string is called great if it is empty or if there are no two adjacent characters x
and y
such that:
x
is a lowercase letter and y
is the same letter but in uppercase (or vice versa).To make the string great, you can choose two adjacent characters that make the string not great and remove them. You can keep doing this until the string becomes great.
Return the string after making it great. The returned string should be in lowercase.
s
be empty?
s
can be empty.To solve this problem, we need to process the string and eliminate pairs of adjacent characters where one is the lowercase equivalent of the other in uppercase. We can utilize a stack to manage this in an efficient manner.
This approach ensures we process the string in one pass with efficient removal and addition operations using the stack.
def makeGood(s: str) -> str:
stack = []
for char in s:
if stack and ((char.islower() and stack[-1] == char.upper()) or (char.isupper() and stack[-1] == char.lower())):
stack.pop() # Remove the problematic pair
else:
stack.append(char) # Add current character to the stack
return ''.join(stack)
# Example usage
s = "leEeetcode"
print(makeGood(s)) # Output: "leetcode"
This code uses a stack to dynamically manage conflicts between adjacent characters and ensures the resultant string is “great” as per the given criteria.
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?