Remove Consecutive Duplicates

This program removes consecutive duplicate characters.

Problem Statement

Write a Java program to remove consecutive duplicates from "aaabbc".

Source Code

1 public class RemoveConsecutiveDuplicates {
2 public static void main(String[] args) {
3 System.out.println("Eduinq Remove Consecutive Duplicates");
4 String str="aaabbc";
5 StringBuilder result=new StringBuilder();
6 result.append(str.charAt(0));
7 for(int i=1;i<str.length();i++){
8 if(str.charAt(i)!=str.charAt(i-1)) result.append(str.charAt(i));
9 }
10 System.out.println("After removal: "+result.toString());
11 }
12 }

Program Output

Eduinq Remove Consecutive Duplicates
After removal: abc

Explanation

The loop compares each character with the one before it and only appends it to the result if it differs from the previous character, together removing consecutive duplicate characters.

Quick Links to Explore