【发布时间】:2021-03-06 00:22:00
【问题描述】:
此程序查找字符串中重复项的计数。
示例 1:
输入:
“阿布德”
输出:
2
说明:
“b”和“d”是两个重复项。
示例 2:
输入:
“eefggghii22”
输出:
3
说明:
重复项是“e”、“g”和“2”。
帮我看看这段代码。
public class CountingDuplicates {
public static int duplicateCount(String str1) {
// Write your code here
int c = 0;
str1 = str1.toLowerCase();
final int MAX_CHARS = 256;
int ctr[] = new int[MAX_CHARS];
countCharacters(str1, ctr);
for (int i = 0; i < MAX_CHARS; i++) {
if(ctr[i] > 1) {
// System.out.printf("%c appears %d times\n", i, ctr[i]);
c = ctr[i];
}
}
return c;
}
static void countCharacters(String str1, int[] ctr)
{
for (int i = 0; i < str1.length(); i++)
ctr[str1.charAt(i)]++;
}
}
【问题讨论】:
-
嗯,那句话里有很多内容——你不明白其中的哪一部分?如果你把它分成
int index = str1.charAt(i); ctr[index]++;会帮助你理解它吗?
标签: java arrays string algorithm