字符统计

题目描述:

如果统计的个数相同,则按照ASII码由小到大排序输出 。如果有其他字符,则对这些字符不用进行统计。
实现以下接口:
输入一个字符串,对字符中的各个英文字符,数字,空格进行统计(可反复调用)
按照统计个数由多到少输出统计结果,如果统计的个数相同,则按照ASII码由小到大排序输出
清空目前的统计结果,重新统计
调用者会保证:

输入的字符串以‘\0’结尾。

输入描述:

输入一串字符。

输出描述:

对字符中的各个英文字符(大小写分开统计),数字,空格进行统计,并按照统计个数由多到少输出,如果统计的个数相同,则按照ASII码由小到大排序输出 。如果有其他字符,则对这些字符不用进行统计。

import java.util.*;

public class Main
{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext())
        {
            String str = scanner.nextLine();
            TreeMap<Character, Integer> map = new TreeMap<>();
            for (int i = 0; i < str.length(); i++)
            {
                char ch = str.charAt(i);
                if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch == ' '))
                {
                    if (map.containsKey(ch))
                        map.put(ch, map.get(ch) + 1);
                    else
                        map.put(ch, 1);
                }
            }
            List<Map.Entry<Character, Integer>> list = new LinkedList<>(map.entrySet());
            Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {
                @Override
                public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
                    return o2.getValue() - o1.getValue();
                }
            });
            for (Map.Entry<Character, Integer> m: list)
            {
                System.out.print(m.getKey());
            }
            System.out.println();
        }
    }
}

import java.util.*;

public class Main
{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext())
        {
            String str = scanner.nextLine();
            int[] buckets = new int[256];
            for (int i = 0; i < str.length(); i++)
            {
                if ((str.charAt(i) >= 'a' && str.charAt(i) <= 'z') || (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') || (str.charAt(i) >= '0' && str.charAt(i) <= '9') || (str.charAt(i) == ' '))
                {
                    buckets[str.charAt(i)]++;
                }
            }
            int max = 0;
            for (int i = 0; i < 256; i++)
                if (buckets[i] > max)
                    max = buckets[i];
            
            String res = "";
            for (int i = max; i > 0; i--)
            {
                for (int j = 0; j < 256; j++)
                {
                    if (buckets[j] == i)
                        res += (char)j;
                }
            }
            System.out.println(res);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值