Given a java string, str, its job is to remove all duplicate contiguous characters from the given string.
Examples:
Input: str= “azxxzy” Output: ay Removal of “xx” modifies the string to “azzy”. Now, the removal of “zz” modifies the string to “ay”. Since the string “ay” doesn’t contain duplicates, the output is ay. Input: “aaccdd” Output: Empty String
Recursive Approach: Refer to the article Recursively remove all adjacent duplicates to solve this problem recursively.
String Functions-based Approach: For more information, see this article Removing the first contiguous pair of similar characters until the pop_back() and back() built-in string methods resolves this issue.
Stack-based Approach: The problem can be solved by using Stack to use the LIFO property. The idea is to move the string from left to right and see if the stack is empty or the top element of the stack doesn't match the current str character, then hit the current character on the stack. Otherwise, remove the item from the top of the stack. To fix the problem, do the following:
// Java program to implement // the above approach import java.util.*; class GFG{ // Function to remove adjacent // duplicate elements static String ShortenString(String str1) { // Store the String without // duplicate elements Stack st = new Stack(); // Store the index of str int i = 0; // Traverse the String str while (i < str1.length()) { // Checks if stack is empty // or top of the stack is not // equal to current character if (st.isEmpty() || str1.charAt(i) != st.peek()) { st.add(str1.charAt(i)); i++; } // If top element of the stack is // equal to the current character else { st.pop(); i++; } } // If stack is empty if (st.isEmpty()) { return ("Empty String"); } // If stack is not Empty else { String short_String = ""; while (!st.isEmpty()) { short_String = st.peek() + short_String; st.pop(); } return (short_String); } } // Driver Code public static void main(String[] args) { String str1 ="azzxzy"; System.out.print(ShortenString(str1)); } } // This code is contributed by Rajput-Ji
Output:
axzy