C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Table: This char array stores all the characters that have been encountered in the string. It needs to be able to fit all the chars.
Result: In this array we place the result chars as we generate them. All duplicate chars are removed.
Exists: For each char, we scan the table with a for-loop to see if the char has already been added. If not, we add it to both arrays.
ForJava program that remove duplicate chars
public class Program {
public static String removeDuplicateChars(String value) {
int length = value.length();
// This table stores characters that have been encountered.
char[] table = new char[length];
int tableLength = 0;
// This array stores our result string.
char[] result = new char[length];
int resultLength = 0;
for (int i = 0; i < value.length(); i++) {
char current = value.charAt(i);
// See if this character has already been encountered.
// ... Test the table for a match.
boolean exists = false;
for (int y = 0; y < tableLength; y++) {
if (current == table[y]) {
exists = true;
break;
}
}
// If char has not been encountered, add it to our result array.
if (!exists) {
table[tableLength] = current;
tableLength++;
result[resultLength] = current;
resultLength++;
}
}
// Return the unique char string.
return new String(result, 0, resultLength);
}
public static void main(String[] args) {
// Test the removeDuplicateChars method.
String test = "Java is cool";
String result = removeDuplicateChars(test);
System.out.println(result);
test = "areopagitica";
result = removeDuplicateChars(test);
System.out.println(result);
}
}
Output
Jav iscol
areopgitc
Tip: This algorithm limits the search for duplicate chars to the number of unique chars, not the total number of chars in the string.
Tip 2: This improves the performance of the method on long strings. An even faster method could store chars by their ASCII values.