File tree Expand file tree Collapse file tree 1 file changed +23
-2
lines changed Expand file tree Collapse file tree 1 file changed +23
-2
lines changed Original file line number Diff line number Diff line change
1
+ // Program to remove duplicates from a given string
2
+ // 1. getUniqueString(String) method uses a boolean array.
3
+ // 2. removeDuplicates(String) method uses a hash map.
4
+ // Both the methods have O(n) space and time complexity. (n being the string length)
5
+
6
+ import java .util .HashMap ;
7
+
1
8
public class RemoveDuplicatesFromString {
2
9
public static void main (String [] args ) {
3
10
RemoveDuplicatesFromString rsd = new RemoveDuplicatesFromString ();
4
11
String input = "Tree Traversal" ;
5
- System .out .println (rsd .getUniqueString (input ));
12
+ System .out .println ("Method 1: " +rsd .getUniqueString (input ));
13
+ System .out .println ("Method 2: " +rsd .removeDuplicates (input ));
6
14
}
7
15
8
16
public String getUniqueString (String input ) {
@@ -17,4 +25,17 @@ public String getUniqueString(String input) {
17
25
}
18
26
return sb .toString ();
19
27
}
20
- }
28
+
29
+ public String removeDuplicates (String input ) {
30
+ HashMap <Character , Integer > map = new HashMap <>();
31
+ StringBuffer sb = new StringBuffer ("" );
32
+ for (int i = 0 ; i < input .length (); i ++) {
33
+ char c = input .charAt (i );
34
+ if (!map .containsKey (c )) {
35
+ sb .append (c );
36
+ map .put (c , 1 );
37
+ }
38
+ }
39
+ return sb .toString ();
40
+ }
41
+ }
You can’t perform that action at this time.
0 commit comments