java - 使用带有 java 的 for 循环计算给定字符串中字符的出现次数
问题描述
这是参考代码:
// Create an array of size 256 i.e. ASCII_SIZE
int count[] = new int[MAX_CHAR];
int len = str.length();
// Initialize count array index
for (int i = 0; i < len; i++)
count[str.charAt(i)]++;
// Create an array of given String size
char ch[] = new char[str.length()];
for (int i = 0; i < len; i++) {
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++) {
// If any matches found
if (str.charAt(i) == ch[j])
find++;
}
if (find == 1)
System.out.println("Number of Occurrence of " +
str.charAt(i) + " is:" + count[str.charAt(i)]);
}
输出应该类似于:
“x”的出现次数是:“它发生的次数”
如果该字母以前出现过,则仅显示该出现一次。
我使用 2 个 for 循环得到了逻辑,尽管我的老师说它可以只使用 1 个 for 循环来执行这个应用程序。
我遇到的问题是:
只有当角色彼此相邻时,我才能找到是否已经找到角色。
您如何检查是否在没有另一个 for 循环的情况下找到了所有先前的字符?
解决方案
使用Map<Integer, Integer>
(键:字符,值:字符数)来存储您的字符数。
你只需要循环你的角色一次:
String input = "this is input string";
Map<Integer, Integer> charCount = new LinkedHashMap<>();
for (int c : input.toCharArray()) {
if (!charCount.containsKey(c)) {
charCount.put(c, 1);
} else {
charCount.put(c, charCount.get(c) + 1);
}
}
// Here you print the char count:
for (Entry<Integer, Integer> entry : charCount.entrySet()) {
// (char) entry.getKey() is the character
// entry.getValue() is number of occurence
}
没有Map
:
int[][] count = new int[MAX_CHAR][2];
for (int c : input.toCharArray()) {
count[c][0] += 1; // Increase occurrence by 1
count[c][1] = 1; // Mark this character exists in string
}
// Here you can print the count of char per character
// Not that, you can use count[c][1] to determine that if the character exists in your String
for (int i = 0; i < MAX_CHAR; i++) {
if (count[i][1] == 1) {
System.out.println("Char: " + (char) i + " Occurence: " + count[i][0]);
}
}
编辑 正如@oreh 建议的那样,我们甚至不需要二维数组:
int[] count = new int[MAX_CHAR];
for (int c : input.toCharArray()) {
count[c][0] += 1; // Increase occurrence by 1
}
for (int i = 0; i < MAX_CHAR; i++) {
if (count[i] > 0) {
System.out.println("Char: " + (char) i + " Occurence: " + count[i]);
}
}
推荐阅读
- reactjs - 当 React 已经在更改 select2 上呈现时,无法刷新更新
- python - Python - 正则表达式将数据框中的一列拆分为 2
- android - 如何存储 Google ARCore 锚点的位置?
- android - 视图未占用全宽 - ConstraintLayout - RecyclerView - Android
- javascript - 如何将传递函数作为道具发送给子组件
- python - Discord.py 加载 json 数据
- image - 在 Flutter 中使旋转后的图像适合屏幕
- sql - 所有列上的like子句
- amazon-web-services - NGNIX redirect_uri 与 AWS Cognito
- r - R中行的条件切片