题解 | #字符串排序#

字符串排序

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

import java.util.Scanner;

import java.util.Arrays;
import java.util.Comparator;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int count = in.nextInt();
        in.nextLine();
        String[] param = new String[count];
        int index = 0;
        // 注意 hasNext 和 hasNextLine 的区别
        while (index < count) { // 注意 while 处理多个 case
            param[index] = in.nextLine();
            index++;
        }
        solution(param);
    }

    private static void solution(String[] param) {

        Arrays.sort(param, new Comparator<String>() {
            public int compare(String a, String b) {
                int pos = 0;
                while (pos < a.length() || pos < b.length()) {

                    if (a.length() < pos + 1) {
              
                        return -1;
                    }
                    if (b.length() < pos + 1) {
                 
                        return 1;
                    }
                    if (a.charAt(pos) == b.charAt(pos)) {
                        pos++;
                        continue;
                    }
                    return a.charAt(pos) > b.charAt(pos) ? 1 : -1;
                }
                return 0;
            }
        });
        for (String word : param) {
            System.out.println(word);
        }
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务