Codewars题记 :Count the number of Duplicates

1、题目:

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 (`b` and `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

2、我的解决方案

 1 class CountingDuplicates {
 2     public static int duplicateCount(String text) {
 3         
 4         Map<Character, Integer > map = new HashMap<Character, Integer>();
 5         
 6         for (Character one : text.toLowerCase().toCharArray()) {
 7             if (map.containsKey(one)) {
 8                 Integer sum = map.get(one);
 9                 sum++;
10                 map.put(one, sum);
11             } else {
12                 map.put(one, 1);
13             }
14         }
15         
16         int result = 0;
17         
18         for (Entry<Character, Integer> entry : map.entrySet()) {
19             if (entry.getValue()>1) {
20                 result++;
21             }
22         }
23         
24         return result;
25     }
26 }

3、最佳解决方案

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;
  }
}

4、总结
  最佳解决方案每次将一个字符截取出来然后查找,查找完后就会把字符串中这个字符删除掉,再进行下一轮查找。

 

转载于:https://www.cnblogs.com/RivenLw/p/11260703.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值