题解 | 名字的漂亮度

名字的漂亮度

https://www.nowcoder.com/practice/02cb8d3597cf416d9f6ae1b9ddc4fde3

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
       int n=in.nextInt();
       in.nextLine();
       for(int i=0;i<n;i++){
            int res=0;
            String str=in.nextLine();
            int[] count=new int[26];
            for(int j=0;j<str.length();j++){
                char ch=str.charAt(j);
                count[ch-'a']++;
            }
            Arrays.sort(count);
            for(int k=26;k>=1;k--){
                res=res+k*count[k-1];
            }
            System.out.println(res);
       }
    }
}

in.nextInt() 只读取整数,不会消费行尾的换行符(\n)。下一次调用 in.nextLine() 时,会立即读取到这个残留的换行符,导致 str 变成一个空字符串 ""。

全部评论

相关推荐

程序员小白条:排版,格式难顶,换个简洁的,保底offer没问题
你的简历改到第几版了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务