Count the number of Duplicates

2017-05-14
次阅读
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 alphanumeric characters, including digits, uppercase and lowercase alphabets.

Example

"abcde" -> 0    # no characters repeats more than once
"aabbcde" -> 2    # 'a' and 'b'
"aabbcdeB" -> 2    # 'a' and 'b'
"indivisibility" -> 1    # 'i'
"Indivisibilities" -> 2    # 'i' and 's'
"aa11" -> 2    # 'a' and '1'

解题思路

函数功能:计算字符串中重复的字符有多少个。我们只要先判断字符是否重复,然后再计算有多少个字符重复。

代码示例

using System;
using System.Linq;

public class Kata
{
  public static int DuplicateCount(string str)
  {
        // 将字符串转成char数组
        char[] charArr = str.ToLower().ToCharArray();
        // 定义int类型数组,用于储存字符重复次数
        int[] arr = new int[123];
        foreach (char item in charArr)
        {
            // 将char类型转成int类型,并作为数组的key
            arr[(int)item]++;
        }
        // 找出重复次数大于2的字符,并返回总数
        return arr.Where(e => e >= 2).Count();
  }
}

其他网友的答案

using System;
using System.Linq;
public class Kata{  
    public static int DuplicateCount(string str)  
    {    
        return str.ToList().GroupBy(x => Char.ToLower(x)).ToDictionary(x => x.Key, x => x.Count()).Where(d => d.Value >= 2).Select(v => v).Count();
    }
}
using System;
using System.Text.RegularExpressions;
using System.Linq;
public class Kata{  
    public static int DuplicateCount(string str)  
    {
        str = String.Join("", str.ToLower().OrderBy(c => c));
        return Regex.Matches(str, @"(.)\1+").Count;
    }
}

题目地址:Train: Counting Duplicates | Codewars

这是一篇过去很久的文章,其中的信息可能已经有所发展或是发生改变。

本文作者:她和她的猫
本文地址https://her-cat.com/posts/2017/05/14/count-the-number-of-duplicates/
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!