如何编写Java函数来计算一个字符串中重复字符的数量?
发布时间:2023-05-26 08:12:08
在Java中编写一个函数来计算一个字符串中重复字符的数量,可以使用HashMap来存储每个字符以及它们出现的次数。具体实现步骤如下:
1. 创建一个HashMap对象来存储字符和出现次数:
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
2. 遍历输入字符串的字符,如果该字符在map中不存在,则将该字符作为key,值设置为1;如果该字符已经存在,则将其对应的值加一。
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
3. 遍历map中的所有entry,统计出现次数大于1的字符的数量。代码如下:
int count = 0;
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() > 1) {
count++;
}
}
return count;
完整的代码如下:
public static int countDuplicateChars(String str) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
int count = 0;
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() > 1) {
count++;
}
}
return count;
}
该函数接受一个String类型的参数,返回一个int类型的结果,表示输入字符串中出现重复字符的数量。可以通过调用该函数来计算一个字符串中重复字符的数量。例如,下面的代码将计算输入字符串"hello world"中出现重复字符的数量:
int count = countDuplicateChars("hello world");
System.out.println(count);
结果为2,因为字符'l'和字符'o'都出现了2次。
