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.
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.
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:
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.
aabbbcdd Your new String is abcd
Submitted by Jasdeep Singh (Jasdeep13)
Download packets of source code on Coders Packet
Comments