计算出现次数和次数打印最高出现的字符“n”次
我试图解决一些程序,我遇到了这个有趣的程序,我们需要打印出现次数最多的字符 n 次 &对于其他角色也是如此。
例如:输入字符串:“请保持水分” 输出字符串:“aaaeeettyysplhdr”
我只能解决一半,我们打印出现次数最多的字符&使用 HashMap 来记录它发生的次数。
public static void repeatedChar(String str) {
char[] chars = str.toCharArray();
Map<Character, Integer> map = new HashMap<>();
for (Character c : chars) {
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
//Now To find the highest character repeated
int max = 0;
//setting to a by default
char maxCharacter = 'a';
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ": Value " + entry.getValue());
if (max < entry.getValue()) {
max = entry.getValue();
maxCharacter = entry.getKey();
}
}
System.out.println("Max Character = " + maxCharacter + " Max Count : " + max);
}
当前打印出现次数最多的字符 &该字符出现的次数。有人可以让我知道如何进一步进行吗?谢谢
I was trying to solve some programs, I came across this interesting one, where we need to print the highest occurred character n times & likewise for other characters.
Ex: Input string : "please stay hydrated"
Output string : "aaaeeettyysplhdr"
I was only able to solve half way, where we print the highest occurred character & the times it has occurred using a HashMap.
public static void repeatedChar(String str) {
char[] chars = str.toCharArray();
Map<Character, Integer> map = new HashMap<>();
for (Character c : chars) {
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
//Now To find the highest character repeated
int max = 0;
//setting to a by default
char maxCharacter = 'a';
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ": Value " + entry.getValue());
if (max < entry.getValue()) {
max = entry.getValue();
maxCharacter = entry.getKey();
}
}
System.out.println("Max Character = " + maxCharacter + " Max Count : " + max);
}
This currently prints the highest occured character & the number of times that character has occurred. Can someone please let me know how to proceed further? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了获得所需的输出,您需要按值对地图进行排序。但由于哈希图并不是要排序的,而是要快速访问的,因此您可以将所有条目添加到列表中并对列表进行排序。像这样:
如果你喜欢流方法:
In order to get the desired output you need to sort your map by value. But since a hashmap is not meant to be sorted, but accessed fast, you could add all entries to a list and sort the list. Something like:
and if you fancy a stream approach: