Remove adjacent duplicate characters from a string

Given a string, remove adjacent duplicates characters from it. In other words, remove all consecutive same characters except one.

Output: ABCD 
public class RemoveDuplicates {

	public String removeDuplicateChars(char[] chars) {
		char prev = '\0';
		int k = 0;
		for (char c : chars) {
			if (prev != c) {
				chars[k] = c;
				prev = c;
				k = k + 1;
		return new String(chars).substring(0, k);

	public static void main(String[] args) {
		RemoveDuplicates testApp = new RemoveDuplicates();
		String str = testApp.removeDuplicateChars("AAABBBCCAAA".toCharArray());


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s