计算出现次数和次数打印最高出现的字符“n”次

发布于 2025-01-16 20:09:56 字数 1163 浏览 0 评论 0原文

我试图解决一些程序,我遇到了这个有趣的程序,我们需要打印出现次数最多的字符 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无声静候 2025-01-23 20:09:57

为了获得所需的输出,您需要按值对地图进行排序。但由于哈希图并不是要排序的,而是要快速访问的,因此您可以将所有条目添加到列表中并对列表进行排序。像这样:

import java.util.Map.Entry;
import java.util.Comparator;


....

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);
        }
    }

    //add map entries to list
    List<Entry<Character, Integer>> list = new ArrayList<>(map.entrySet());
    //sort entries by value descending
    list.sort(Entry.comparingByValue(Comparator.reverseOrder()));

    //print
    for (Entry<Character, Integer> entry : list) {
        for (int i = 0; i < entry.getValue(); i++){
            System.out.print(entry.getKey());
        }
    }
}

如果你喜欢流方法:

import java.util.Comparator;
import java.util.Map;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

....


public static void repeatedCharWithStreams(String str) {
    String output =
            Pattern.compile("")
                    .splitAsStream(str)
                    .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
                    .entrySet().stream()
                    .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                    .map(e -> e.getKey().repeat(e.getValue().intValue()))
                    .collect(Collectors.joining());

    System.out.println(output);
}

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:

import java.util.Map.Entry;
import java.util.Comparator;


....

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);
        }
    }

    //add map entries to list
    List<Entry<Character, Integer>> list = new ArrayList<>(map.entrySet());
    //sort entries by value descending
    list.sort(Entry.comparingByValue(Comparator.reverseOrder()));

    //print
    for (Entry<Character, Integer> entry : list) {
        for (int i = 0; i < entry.getValue(); i++){
            System.out.print(entry.getKey());
        }
    }
}

and if you fancy a stream approach:

import java.util.Comparator;
import java.util.Map;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

....


public static void repeatedCharWithStreams(String str) {
    String output =
            Pattern.compile("")
                    .splitAsStream(str)
                    .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
                    .entrySet().stream()
                    .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                    .map(e -> e.getKey().repeat(e.getValue().intValue()))
                    .collect(Collectors.joining());

    System.out.println(output);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文