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);
}
}