-
Notifications
You must be signed in to change notification settings - Fork 1
/
Challenge14.java
52 lines (46 loc) · 1.38 KB
/
Challenge14.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
package challenge14;
import static org.junit.Assert.assertTrue;
import java.util.LinkedHashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
/**
* The Class Challenge14. remove duplicate characters from String? This is one
* of the interesting String question, which also has lots of variants. You need
* to remove duplicate characters from a given string keeping only the first
* occurrences. For example, if the input is ‘bananas’ the output will be
* ‘bans’. Pay attention to what output could be, because if you look closely
* original order of characters are retained the in output
*
*/
public class Challenge14 {
/**
* Removes the duplicates.
*
* @param input
* the input
* @return the string
*/
public static String removeDuplicates(String input) {
if (input == null || input.isEmpty()) {
throw new IllegalArgumentException("invalid input found");
}
Set<Character> unique = new LinkedHashSet<Character>();
for (Character c : input.toCharArray()) {
unique.add(c);
}
StringBuffer buffer = new StringBuffer();
for (Character c : unique) {
buffer.append(c);
}
return buffer.toString();
}
/**
* Test.
*/
@Test
public void test() {
String output = Challenge14.removeDuplicates("madam");
System.out.println(output);
assertTrue("mad".equals(output));
}
}