Advertisement
Passant_Ibrahem

Untitled

Jul 21st, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.18 KB | None | 0 0
  1. // function takes a char array as input.
  2. // modifies it to remove duplicates and adds a 0 to mark the end
  3. // of the unique chars in the array.
  4. public static void removeDuplicates(char[] str) {
  5.   if (str == null) return; // if the array does not exist..nothing to do return.
  6.   int len = str.length; // get the array length.
  7.   if (len < 2) return; // if its less than 2..can't have duplicates..return.
  8.   int tail = 1; // number of unique char in the array.
  9.   // start at 2nd char and go till the end of the array.
  10.   for (int i = 1; i < len; ++i) {
  11.     int j;
  12.     // for every char in outer loop check if that char is already seen.
  13.     // char in [0,tail) are all unique.
  14.     for (j = 0; j < tail; ++j) {
  15.       if (str[i] == str[j]) break; // break if we find duplicate.
  16.     }
  17.     // if j reachs tail..we did not break, which implies this char at pos i
  18.     // is not a duplicate. So we need to add it our "unique char list"
  19.     // we add it to the end, that is at pos tail.
  20.     if (j == tail) {
  21.       str[tail] = str[i]; // add
  22.       ++tail; // increment tail...[0,tail) is still "unique char list"
  23.     }
  24.   }
  25.   str[tail] = 0; // add a 0 at the end to mark the end of the unique char.
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement