题目
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 (
band
B)
“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
题解
做了这么几道题,基本上对于Collection和Stream有了一些了解,不用每次写搜索引擎了。思路非常直接,就是先生成一个词频映射,然后对于词频映射的Value值找大于1的个数——
import java.util.*; import java.io.*; import java.util.stream.*; class CountingDuplicates { public static int duplicateCount(String text) { HashMap<Character,Integer> map = new HashMap<Character,Integer>(); for (int i=0;i<text.length();i++) { Character c = new Character(text.charAt(i)); Integer v = map.get(c); if (v == null) map.put(c,1); else map.put(c,v+1); } Stream<Integer> si = map.values().stream(); return (int)si.filter(x->(x>1)).count(); } }
标准解法没有什么非常特别的。