Search⌘ K
AI Features

Removing Duplicates in a String

Explore how to remove consecutive duplicate characters from a string using recursion in Java. Understand the base and recursive cases with a step-by-step code explanation to solve string problems effectively during coding interviews.

What does removing duplicates mean?

When given a string that has repeating adjacent characters, we only want to keep one of each character. To do this, we must eliminate the repeating characters.

The illustration below shows this process.

Implementing the code

The code below shows how to do this with recursion. First, let’s see the code, and then we will go on to its explanation.

Try the code by changing the value of text to see how it works with other strings.

Java
class RemoveDuplicatesClass {
private static String remDuplicates(String text) {
if (text.length() == 1) {
return text;
}
if (text.substring(0,1).equals(text.substring(1,2))) {
return remDuplicates(text.substring(1));
}
else {
return text.substring(0,1) + remDuplicates(text.substring(1));
}
}
public static void main( String args[] ) {
String input1 = "Helloo";
String input2 = "Thiss iiss aa teesstt";
System.out.println( "Original string: " + input1);
String output = remDuplicates(input1);
System.out.println("String after: " + output);
}
}

Understanding the code

The recursive code can be broken down into two parts: the recursive method and the main method where ...