Remove first adjacent pairs of similar characters until possible - GeeksforGeeks

27 May, 2021
Given a string Str, the task is to remove first adjacent pairs of similar characters until we can. Note: Remove adjacent characters to get a new string and then again remove adjacent duplicates from the new string and keep repeating this process until all similar adjacent character pairs are removed.Examples:  
Input: str = “keexxllx” Output: kx Step 0: Remove ee to get “kxxllx” Step 1: Remove xx to get “kllx” Step 2: Remove ll to get “kx” Input: str = “abbaca” Output: ca  
 
Approach: Use string’s back() and pop_back() method STL in C++ to solve the above problem. Iterate for every character in the string, and if the adjacent characters are same, then remove the adjacent characters using pop_back() function. At the end, return the final string. Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to remove adjacent duplicatesstring removeDuplicates(string S){    string ans = "";     // Iterate for every character    // in the string    for (auto it : S) {         // If ans string is empty or its last        // character does not match with the        // current character then append this        // character to the string        if (ans.empty() or ans.back() != it)            ans.push_back(it);         // Matches with the previous one        else if (ans.back() == it)            ans.pop_back();    }     // Return the answer    return ans;} // Driver Codeint main(){    string str = "keexxllx";    cout << removeDuplicates(str);}
// Java implementation of the above approachclass GFG{     // Function to remove adjacent duplicates    static String removeDuplicates(String S)    {        String ans = "";         // Iterate for every character        // in the string        for (int i = 0; i < S.length(); i++)        {             // If ans string is empty or its last            // character does not match with the            // current character then append this            // character to the string            if (ans.isEmpty() ||                ans.charAt(ans.length() - 1) != S.charAt(i))                ans += S.charAt(i);             // Matches with the previous one            else if (ans.charAt(ans.length() - 1) == S.charAt(i))                ans = ans.substring(0, ans.length() - 1);        }         // Return the answer        return ans;    }     // Driver Code    public static void main(String[] args)    {        String str = "keexxllx";        System.out.println(removeDuplicates(str));    }} // This code is contributed by// sanjeev2552
# Python3 implementation of the above approach # Function to remove adjacent duplicatesdef removeDuplicates(S) :     ans = "";     # Iterate for every character    # in the string    for it in S :         # If ans string is empty or its last        # character does not match with the        # current character then append this        # character to the string        if (ans == "" or ans[-1] != it) :            ans += it ;         # Matches with the previous one        elif (ans[-1] == it) :            ans = ans[:-1];     # Return the answer    return ans;  # Driver Codeif __name__ == "__main__" :     string = "keexxllx";    print(removeDuplicates(string));     # This code is contributed by AnkitRai01
// C# implementation of the above approachusing System;     class GFG{     // Function to remove adjacent duplicates    static String removeDuplicates(String S)    {        String ans = "";         // Iterate for every character        // in the string        for (int i = 0; i < S.Length; i++)        {             // If ans string is empty or its last            // character does not match with the            // current character then append this            // character to the string            if (ans == "" ||                ans[ans.Length - 1] != S[i])                ans += S[i];             // Matches with the previous one            else if (ans[ans.Length - 1] == S[i])                ans = ans.Substring(0, ans.Length - 1);        }         // Return the answer        return ans;    }     // Driver Code    public static void Main(String[] args)    {        String str = "keexxllx";        Console.WriteLine(removeDuplicates(str));    }} // This code is contributed by Rajput-Ji
<script> // JavaScript implementation of the above approach // Function to remove adjacent duplicates     function removeDuplicates( S) {        var ans = "";         // Iterate for every character        // in the string        for (i = 0; i < S.length; i++) {             // If ans string is empty or its last            // character does not match with the            // current character then append this            // character to the string            if (ans.length==0 ||            ans.charAt(ans.length - 1) != S.charAt(i))                ans += S.charAt(i);             // Matches with the previous one            else if (ans.charAt(ans.length - 1) == S.charAt(i))                ans = ans.substring(0, ans.length - 1);        }         // Return the answer        return ans;    }     // Driver Code             var str = "keexxllx";        document.write(removeDuplicates(str)); // This code contributed by Rajput-Ji </script>
kx
 
ankthon
sanjeev2552
Rajput-Ji
STL
C++ Programs
Strings
Strings
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Dynamic _Cast in C++
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4