Created
November 6, 2016 16:22
-
-
Save nashid/97040a01f2df94ced69cfc7dbdb1e8f7 to your computer and use it in GitHub Desktop.
Replace duplicate characters from a string and leave the first occurrence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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