Count the number of Duplicates
Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.
Example
"abcde" -> 0 # no characters repeats more than once
"aabbcde" -> 2 # 'a' and 'b'
"aabBcde" -> 2 # 'a' occurs twice and 'b' twice (bandB)
"indivisibility" -> 1 # 'i' occurs six times
"Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice
"aA11" -> 2 # 'a' and '1'
"ABBA" -> 2 # 'A' and 'B' each occur twice
Good Solution1:
public class CountingDuplicates {
public static int duplicateCount(String text) {
int ans = 0;
text = text.toLowerCase();
while (text.length() > 0) {
String firstLetter = text.substring(0,1);
text = text.substring(1);
if (text.contains(firstLetter)) ans ++;
text = text.replace(firstLetter, "");
}
return ans;
}
}
Good Solution2:
import java.util.Map;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
class CountingDuplicates {
private static Map<Character, Long> charFrequenciesMap(final String text) {
return text.codePoints()
.map(Character::toLowerCase)
.mapToObj(c -> (char) c)
.collect(groupingBy(identity(), counting()));
}
static int duplicateCount(final String text) {
return (int) charFrequenciesMap(text).values().stream()
.filter(i -> i > 1)
.count();
}
}