Coders Packet

Remove Consecutive duplicate characters from a string in Java using recursion.

By Jasdeep Singh

In this tutorial, we will learn how to remove duplicate characters from a given string using the Java program. We will learn it using recursion method.

Understanding the Problem

In this problem we will be a String containing consecutive duplicate characters For ex: aabbbcddd we have to return result as abcd. String is thecollection of characters so in this problem we will be checking all the characters in the given string and then we will remove all the consecutive duplicate characters and then return the string.

Sometimes recursion can be a bit tricky. Recursion is a method of solving a particular problem in which we calculate the solution only by using a smaller instance of the same problem. In programming, recursion using a function that calls itself directly or indirectly and that corresponding function is called as recursive function.

Program to find out Consecutive double.

import java.util.Scanner;
class duplicateChar {
  public static String removeCosecutiveDuplicates(String s) {
    if(s.length()<=1) {
      return s;
    }
    if(s.charAt(0) == s.charAt(1)) {
      return removeCosecutiveDuplicates(s.substring(1));
    }
    else {
      String small = removeCosecutiveDuplicates(s.substring(1));
      return s.charAt(0) + small;
    }
  }
  
  public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
     String str  = s.nextLine();
     String result = removeCosecutiveDuplicates(str);
     s.close();
     System.out.println("Your new String is " + result);
    
  }

}

There are three parts in a recursive function:

  1. Base case
  2. Recursive case
  3. Small calculations

Base case for this function is that it will terminate and return string when the length of string is less than or equal to 1. Length of string is calculate by using lenght().

In the recursive condition, we call the function itself, and while execution string increase its value by 1 and each time it moves to next character of string. Hence, after each method call is executed we will get the result as our string after removing duplicate consecutive characters which is returned to main as result. Finally, we will print this value calling print function.

Output of this Problem

aabbbcdd
Your new String is abcd

 

Download Complete Code

Comments

No comments yet