LeetCode 1544: Make The String Great Solution
Master LeetCode problem 1544 (Make The String Great), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To solve this problem, we can iterate through the input string and check if two adjacent characters are in the form of "lower-upper" or "upper-lower". If such a pair is found, we remove them and continue the process until no more such pairs can be removed. This can be done efficiently using a stack data structure.
Algorithmic Idea
- Initialize a stack to store characters.
- Iterate through each character in the input string.
- If the stack is not empty and the current character combined with the top character of the stack form a bad pair, pop the character from the stack.
- Otherwise, push the current character onto the stack.
- Finally, construct the resulting string using the characters left in the stack.
Time Complexity
The time complexity of this approach is O(n), where n is the length of the input string.
Space Complexity
The space complexity of this approach is O(n) to store the characters in the stack.
Solution Code
class Solution {
public String makeGood(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (!stack.isEmpty() && Math.abs(stack.peek() - c) == 32) {
stack.pop();
} else {
stack.push(c);
}
}
StringBuilder sb = new StringBuilder();
for (char c : stack) {
sb.append(c);
}
return sb.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1544 (Make The String Great)?
This page provides optimized solutions for LeetCode problem 1544 (Make The String Great) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1544 (Make The String Great)?
The time complexity for LeetCode 1544 (Make The String Great) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1544 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1544 in Java, C++, or Python.