题解 | #字符串排序#

字符串排序

https://www.nowcoder.com/practice/5af18ba2eb45443aa91a11e848aa6723

// 用一个map记录字符串出现次数,用一个treeset排序。
import java.util.Scanner;
import java.util.TreeSet;
import java.util.Iterator;
import java.util.HashMap;
import java.util.Map;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        in.nextLine();
        // String[] arr = new String[n];
        TreeSet<String> set = new TreeSet<String>();
        Map<String, Integer> map = new HashMap<>();
        String temp = null;
        for(int i=0;i<n;i++) {
            temp = in.nextLine();
            if(map.containsKey(temp)) {
                map.put(temp, map.get(temp)+1);
            } else {
                map.put(temp, 1);
                set.add(temp);
            }            
        }
        Iterator<String> i = set.iterator();
        while(i.hasNext()) {
            String p = i.next();            
            int q = map.get(p);
            for(int j=0;j<q;j++) {
                System.out.println(p);
            }
        }
    }
}

全部评论

相关推荐

02-04 17:01
南昌大学 Java
牛客96763241...:拿插件直接投就完了,这玩意看运气的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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