思路解释

  1. 读取输入数据

    • 从输入中分离字典单词、待查找单词和第 个兄弟单词的信息。
  2. 通过自定义函数判断是否为兄弟单词

    • 检查长度是否相等。
    • 判断排序后的字符串是否相等。
  3. 筛选出所有兄弟单词并进行字典序排序

  4. 输出总数和第 个兄弟单词

代码实现

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

void async function () {
    // 读取输入数据
    const line = await readline();
    const input = line.split(" ");

    const n = parseInt(input[0]); // 字典中单词数量
    const words = input.slice(1, n + 1); // 字典单词
    const x = input[n + 1]; // 待查找单词
    const k = parseInt(input[n + 2]); // 第 k 个

    // 筛选兄弟单词
    const brothers = words.filter((word) => isBrother(word, x));

    // 输出兄弟单词总数
    console.log(brothers.length);

    if (brothers.length >= k) {
        // 按字典序排序
        brothers.sort();
        // 输出第 k 个
        console.log(brothers[k - 1]);
    }
}()

/**
 * 判断是否是兄弟单词
 * @param {string} word 字典单词
 * @param {string} target 待查找单词
 * @returns {boolean} 是否是兄弟单词
 */
function isBrother(word, target) {
    if (word.length !== target.length || word === target) {
        return false;
    }

    const sortedWord = word.split("").sort().join("");
    const sortedTarget = target.split("").sort().join("");

    return sortedWord === sortedTarget;
}

复杂度分析

时间复杂度

  • 排序操作:单词排序的复杂度为 ,共复杂度为
  • 筛选兄弟单词:遍历单词后筛选复杂度为
  • 兄弟单词排序:兄弟单词数量最多为 ,复杂度为
  • 总时间复杂度

空间复杂度

  • 兄弟单词列表:
  • 字符排序所需空间:,总为
  • 总空间复杂度