Solution Steps
- Obtain char array from the input String
- Loop through the char array, check if the list(List<Character>) already contains the char
- If No, add the char to the list
- If Yes, add the char to the duplicates Set<Character>
- The elements present in the duplicates Set gives us the required output.
package com.java.programs;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class DuplicateCharacters {
public static Set<Character> duplicateCharacters(String input) {
List<Character> list = new ArrayList<>();
Set<Character> duplicates = new TreeSet<>();
for (char c : input.toCharArray()) {
if (list.contains(c)) {
duplicates.add(c);
} else {
list.add(c);
}
}
return duplicates;
}
public static void main(String[] args) {
System.out.println(duplicateCharacters("aeroplane"));
}
}
[a, e]