题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); // 保存单词个数、x单词、x单词的兄弟单词中的第k个 let [n, words, word, num] = [0, [], '', 0] rl.on('line', function (line) { // 分隔出各个字符串 const arr = line.split(' ') // 获取单词个数,并转成数字 const n = arr[0]*1 // 截取出n个单词 const words = arr.slice(1,n + 1) // 截取出x单词 const word = arr[arr.length - 2] // 截取出,k const k = arr[arr.length - 1] // 遍历n个单词,找出兄弟单词放到一个新数组 const res = [] for(let i = 0; i < words.length; i++) { // 判断是不是兄弟单词,且不能和自身一样 if(isBrotherWord(word, words[i])){ res.push(words[i]) } } // 按照字典排列后,分两行打印兄弟单词个数、第k个单词时 res.sort() console.log(res.length) // 有符合的第k个才输出,不然不输出 res[k-1] && console.log(res[k-1]) }); function isBrotherWord(word1:string, word2:string){ // word1 !== word2 就是两个单词不能相等 // w1 === w1 就代表word1与word2两个单词组成一样 const w1 = word1.split('').sort().join() const w2 = word2.split('').sort().join() if(word1 !== word2 && w1 === w2){ return true } return false }