LeetCode 1047: Remove All Adjacent Duplicates In String Solution
Master LeetCode problem 1047 (Remove All Adjacent Duplicates In String), 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 use a stack to keep track of the characters in the input string. We iterate through each character in the string and check if the current character is equal to the top character in the stack. If they are equal, we pop the top character from the stack. Otherwise, we push the current character onto the stack. After iterating through the entire string, the stack will contain the characters of the final string with no adjacent duplicates.
- Time complexity: O(n) where n is the length of the input string
- Space complexity: O(n) where n is the length of the input string
Solution Code
class Solution {
public String removeDuplicates(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (sb.length() > 0 && sb.charAt(sb.length() - 1) == c) {
sb.deleteCharAt(sb.length() - 1);
} else {
sb.append(c);
}
}
return sb.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1047 (Remove All Adjacent Duplicates In String)?
This page provides optimized solutions for LeetCode problem 1047 (Remove All Adjacent Duplicates In String) 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 1047 (Remove All Adjacent Duplicates In String)?
The time complexity for LeetCode 1047 (Remove All Adjacent Duplicates In String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1047 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1047 in Java, C++, or Python.