Skip to content

Instantly share code, notes, and snippets.

@nashid
Created November 6, 2016 16:22
Show Gist options
  • Save nashid/97040a01f2df94ced69cfc7dbdb1e8f7 to your computer and use it in GitHub Desktop.
Save nashid/97040a01f2df94ced69cfc7dbdb1e8f7 to your computer and use it in GitHub Desktop.
Replace duplicate characters from a string and leave the first occurrence
package kata.string;
import java.util.Set;
import java.util.HashSet;
public class ReplaceDuplicates {
/*
* @param input char array with duplicated characters for example, google
* @return output char array with duplicated characters. After removal of duplicated characters output will be gogle
*/
public static char[] replace(char[] input) {
if (null == input) {
return null;
}
Set<Character> characters = new HashSet<>();
int j = 0;
for (int i = 0; i < input.length; i++) {
if (!characters.contains(input[i])) {
characters.add(input[i]);
input[j++] = input[i];
}
}
for (; j < input.length; j++) {
input[j] = '\0';
}
return input;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment