-
Notifications
You must be signed in to change notification settings - Fork 2
/
RemoveDuplicateFromString.java
99 lines (77 loc) · 2.48 KB
/
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package com.interview.notes.code.misc;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
public class RemoveDuplicateFromString {
String removeDuplicatesUsingCharArray(String str) {
char[] chars = str.toCharArray();
StringBuilder sb = new StringBuilder();
int repeatedCtr;
for (int i = 0; i < chars.length; i++) {
repeatedCtr = 0;
for (int j = i + 1; j < chars.length; j++) {
if (chars[i] == chars[j]) {
repeatedCtr++;
}
}
if (repeatedCtr == 0) {
sb.append(chars[i]);
}
}
return sb.toString();
}
String removeDuplicatesUsinglinkedHashSet(String str) {
StringBuilder sb = new StringBuilder();
Set<Character> linkedHashSet = new LinkedHashSet<>();
for (int i = 0; i < str.length(); i++) {
linkedHashSet.add(str.charAt(i));
}
for (Character c : linkedHashSet) {
sb.append(c);
}
return sb.toString();
}
String removeDuplicatesUsingSorting(String str) {
StringBuilder sb = new StringBuilder();
if (!str.isEmpty()) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
sb.append(chars[0]);
for (int i = 1; i < chars.length; i++) {
if (chars[i] != chars[i - 1]) {
sb.append(chars[i]);
}
}
}
return sb.toString();
}
String removeDuplicatesUsingHashSet(String str) {
StringBuilder sb = new StringBuilder();
Set<Character> hashSet = new HashSet<>();
for (int i = 0; i < str.length(); i++) {
hashSet.add(str.charAt(i));
}
for (Character c : hashSet) {
sb.append(c);
}
return sb.toString();
}
String removeDuplicatesUsingIndexOf(String str) {
StringBuilder sb = new StringBuilder();
int idx;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
idx = str.indexOf(c, i + 1);
if (idx == -1) {
sb.append(c);
}
}
return sb.toString();
}
String removeDuplicatesUsingDistinct(String str) {
StringBuilder sb = new StringBuilder();
str.chars().distinct().forEach(c -> sb.append((char) c));
return sb.toString();
}
}