w3resource
Java Programming Exercies

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

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?



New Content: Composer: Dependency manager for PHP, R Programming