Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java String Exercises: Remove all adjacent duplicates recursively from a given string

Java String: Exercise-55 with Solution

Write a Java program to remove all adjacent duplicates recursively from a given string.

Sample Solution:

Java Code:

import java.util.*;
import java.lang.*;
import java.io.*;
class Main
 {
     public static void check(String str)
     {
         if(str.length()<=1)
         {
             System.out.println(str);
             return;
         }
         String n=new String();
         int count=0;
         for(int i=0;i<str.length();i++)
         {
             while(i<str.length()-1 && str.charAt(i)==str.charAt(i+1))
             {
                 if(i<str.length()-2 &&str.charAt(i)!=str.charAt(i+2))
                 i+=2;
                 else
                 i++;
                 count++;
             }
             if(i!=str.length()-1)
             n=n+str.charAt(i);
             else
             {if(i==str.length()-1 && str.charAt(i)!=str.charAt(i-1))
                 n=n+str.charAt(i);
             }
         }
         if(count>0)
         check(n);
         else
         System.out.println(n);
     }

public static void main (String[] args)
  {
    String ab="aabaarbarccrabmq";
    System.out.println("The given string is: "+ab);
    System.out.println("The new string after removing all adjacent duplicates is:");

    check(ab);
    }
}

Sample Output:

The given string is: aabaarbarccrabmq
The new string after removing all adjacent duplicates is:
brmq

Pictorial Presentation:

Java String Exercises: Remove all adjacent duplicates recursively from a given string

Flowchart: 1

Flowchart: Java String Exercises - Remove all adjacent duplicates recursively from a given string

Flowchart: 2

Flowchart: Java String Exercises - Remove all adjacent duplicates recursively from a given string

Visualize Java code execution (Python Tutor):


Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to find the smallest window in a string containing all characters of another string.
Next: Write a Java program to append two given strings such that, if the concatenation creates a double characters then omit one of the characters.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe