-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP40_RemoveDuplicateCharacters.java
More file actions
37 lines (31 loc) · 1.14 KB
/
Copy pathP40_RemoveDuplicateCharacters.java
File metadata and controls
37 lines (31 loc) · 1.14 KB
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
31
32
33
34
35
36
37
package programs;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* ============================================================
* PROGRAM 40: Remove Duplicate Characters from String
* ============================================================
* Problem: WAP to remove all duplicate characters from a string,
* preserving the original order of first appearance.
* - Input : "programming"
* - Output: "progami"
* ============================================================
*/
public class P40_RemoveDuplicateCharacters {
public static String removeDuplicates(String str) {
if (str == null) return null;
Set<Character> seen = new LinkedHashSet<>();
for (char c : str.toCharArray()) {
seen.add(c);
}
StringBuilder sb = new StringBuilder();
for (char c : seen) sb.append(c);
return sb.toString();
}
public static void main(String[] args) {
String[] words = {"programming", "banana", "antigravity", "hello world"};
for (String w : words) {
System.out.printf(" \"%-15s\" -> \"%s\"%n", w, removeDuplicates(w));
}
}
}