Codewars

一、计算重复次数

编写一个函数,该函数将返回在输入字符串中多次出现的不区分大小写的字母字符和数字的计数可以假定输入字符串仅包含字母(大写和小写)和数字。

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`)
"Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice
"aA11" -> 2 # 'a' and '1'
"ABBA" -> 2 # 'A' and 'B' each occur twice

对于"indivisibility" -> 1 # 'i'出现了六次,其结果为1,因为只有'i'重复出现。

 1 import java.util.HashSet;
 2 import java.util.Set;
 3 
 4 public class CountingDuplicates {
 5     public static int duplicateCount(String text) {
 6         // Write your code here
 7         Set list = new HashSet<>();
 8         Set cout = new HashSet<>();
 9         for (Character c : text.toLowerCase().toCharArray()) {
10             if (list.contains(c)) {
11                 cout.add(c);
12             }else {
13                 list.add(c);
14             }
15         }
16         return cout.size();
17       }
18     public static void main(String[] args) {
19         System.out.println(duplicateCount("IndivisibilitiesReturnsTwo"));
20     }
21 }

 

你可能感兴趣的:(Codewars)