# HJ14 字符串排序

https://www.nowcoder.com/practice/5af18ba2eb45443aa91a11e848aa6723 (opens new window)

# 描述

给定 n 个字符串,请对 n 个字符串按照字典序排列。

输入描述:

输入第一行为一个正整数n(1≤n≤1000),下面n行为n个字符串(字符串长度≤100),字符串中只含有大小写字母。

输出描述:

数据输出n行,输出结果为按照字典序排列的字符串。

示例1:

输入:
9
cap
to
cat
card
two
too
up
boat
boot

输出:
boat
boot
cap
card
cat
to
too
two
up

# 解答

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void async function () {
    let line;
    const words = [];

    while(line = await readline()){
        words.push(line);
    }

    words.shift();

    words.sort((word1, word2) => {
        const len = Math.max(word1.length, word2.length);

        for (let i = 0; i < len; i++) {
            const char1 = word1[i];
            const char2 = word2[i];

            if (!char1) {
                return -1;
            }

            if (!char2) {
                return 1;
            }

            const charCode1 = char1.charCodeAt(0);
            const charCode2 = char2.charCodeAt(0);

            if (charCode1 !== charCode2) {
                return charCode1 - charCode2;
            }
        }

        return 0;
    });

    words.forEach((word) => console.log(word));
}()
本章目录