题解 | #字符统计#

字符统计

https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        Map<Character,Integer> map = new HashMap<>();
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String str = in.nextLine();
            char[] chrs = str.toCharArray();
            for(int i=0;i<chrs.length;i++){
                if(map.containsKey(chrs[i])){
                    map.computeIfPresent(chrs[i],(key,value)->value+1);
                }else{
                    map.put(chrs[i],1);
                }
                
            }
            map.entrySet().stream().sorted(
                (o1, o2) -> 
                {
                    if(o1.getValue()-o2.getValue()>0){
                        return -1;
                    }else if(o1.getValue()-o2.getValue()<0){
                        return 1;
                    }else{
                        if(o1.getKey()-o2.getKey()>0){
                            return 1;
                        }else if(o1.getKey()-o2.getKey()<0){
                            return -1;
                        }else{
                            return 0;
                        }
                    }
                }
            ).forEachOrdered(e->{
                System.out.print(e.getKey());
            });
        }
    }
}

全部评论

相关推荐

虚闻松声:继续投吧。 简历没啥问题。很优秀。 拙见:自我评价没什么意义;试试转向Agent开发、大模型应用;别死磕传统Java开发。 免费修改简历,就业咨询,欢迎私信交流。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务