Remove all consecutive duplicates from the string

 

Given a string S, remove all the consecutive duplicates and note that this problem is different from Recursively remove all adjacent duplicates. Here we keep one character and remove all subsequent same characters.
For Example:
Input  : aaaaabbbbbb
Output : ab

Input : sweetinsweet
Output : swetinswet

Input : aabccba
Output : abcba

public class RemoveDuplicate {

 public static void main(String[] args) {

  String str = "aabccba";
  char[] cStr = new char[str.length()];
  int i, k = 0;
  for (i = 0; i < str.length(); i++) {

   if (i == 0) {
    cStr[k++] = str.charAt(i);
   } else {
    if (str.charAt(i) != cStr[k - 1]) {
     cStr[k++] = str.charAt(i);
    }
   }
  }
  str = String.valueOf(cStr, 0, k);
  System.out.println(str);
 }
}
OUTPUT:

abcba


No comments:
Write comments