Counting Duplicates

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();
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • 对于每个有孩子、宠物、家长或其他亲戚的家庭来说,究竟缺什么? 那一定是JIBO这个家庭机器人! JIBO是由美国麻...
    BayMini阅读 2,839评论 0 1
  • 远方的美妙身边的最好走过我的人生路,感激去了的去了吧留下的是幸运那些岁月,已刻在了心里老公说我不是凡人我说不是“烦...
    水一慧心阅读 2,286评论 0 0
  • 昨天看到弗兰克老师新鲜出炉的训练营广告,最关注的就是他的开课时间,一看就和目前的演讲训练营是重叠的,虽然有些不舒服...
    梅子Mey阅读 2,695评论 21 10
  • 1/朋友矛盾无法上课成绩下滑了,怎么办? 你好。爷爷看到你的来信了。 不知你的性别,年龄如何,跟朋友之间发生了什么...
    MABEL梅阅读 3,430评论 0 0

友情链接更多精彩内容