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:
Flowchart: 1
Flowchart: 2
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
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework