- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathRemoveDuplicateFromString.java
30 lines (26 loc) · 945 Bytes
/
RemoveDuplicateFromString.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
packagecom.thealgorithms.others;
/**
* @author Varun Upadhyay (https://github.com/varunu28)
*/
publicfinalclassRemoveDuplicateFromString {
privateRemoveDuplicateFromString() {
}
/**
* Removes duplicate characters from the given string.
*
* @param input The input string from which duplicate characters need to be removed.
* @return A string containing only unique characters from the input, in their original order.
*/
publicstaticStringremoveDuplicate(Stringinput) {
if (input == null || input.isEmpty()) {
returninput;
}
StringBuilderuniqueChars = newStringBuilder();
for (charc : input.toCharArray()) {
if (uniqueChars.indexOf(String.valueOf(c)) == -1) {
uniqueChars.append(c); // Append character if it's not already in the StringBuilder
}
}
returnuniqueChars.toString();
}
}