Skip to content

Commit c94b234

Browse files
committed
Update RemoveDuplicatesFromString.java
1 parent 4f05696 commit c94b234

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

solutions/java/RemoveDuplicatesFromString.java

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,16 @@
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+
18
public class RemoveDuplicatesFromString {
29
public static void main(String[] args) {
310
RemoveDuplicatesFromString rsd = new RemoveDuplicatesFromString();
411
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));
614
}
715

816
public String getUniqueString(String input) {
@@ -17,4 +25,17 @@ public String getUniqueString(String input) {
1725
}
1826
return sb.toString();
1927
}
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+
}

0 commit comments

Comments
 (0)