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.

Input:  AABBBCDDD
 
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());
		System.out.println(str);
	}

}

Leave a Reply

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

WordPress.com Logo

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

Google photo

You are commenting using your Google 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