题解 | #查找兄弟单词#

查找兄弟单词

https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 读取输入
        String str = in.nextLine();
        // 处理输入
        String[] strArr = str.split(" ");
        // 获取单词数量
        int size = Integer.parseInt(strArr[0]);
        String[] words = new String[size];
        // 获取单词数组
        for (int i = 0; i < size; i++) {
            words[i] = strArr[i + 1];
        }
        // 获取“兄弟单词”,并排序处理
        String brotherWord = strArr[size + 1];
        char[] brotherWordSorting = brotherWord.toCharArray();
        Arrays.sort(brotherWordSorting);
        String brotherWordSorted = new String(brotherWordSorting);

        // 获取k
        int k = Integer.parseInt(strArr[size + 2]);
        // 统计兄弟单词数量,用一个有序数组存储
        List<String> brotherWordsList = new ArrayList<>();

        for (int i = 0; i < size; i++) {
            if(words[i].equals(brotherWord)){
                continue;
            }
            String wordSorting;
            char[] thisWord = words[i].toCharArray();
            Arrays.sort(thisWord);
            String wordSorted = new String(thisWord);
            if (words[i].length() == brotherWord.length() && wordSorted.equals(brotherWordSorted)) {
                brotherWordsList.add(words[i]);
            }
        }
        // 排序
        brotherWordsList.sort(String::compareTo);
        // 输出结果
        System.out.println(brotherWordsList.size());
        if (brotherWordsList.size() >= k) {
            System.out.println(brotherWordsList.get(k - 1));
        }

    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 18:05
哈哈哈哈哈感觉朋友找工作的已经疯掉了,直接上图
码农索隆:真老板娘:“我嘞个去,这不我当年的套路吗
点赞 评论 收藏
分享
湫湫湫不会java:先投着吧,大概率找不到实习,没实习的时候再加个项目,然后把个人评价和荣誉奖项删了,赶紧成为八股战神吧,没实习没学历,秋招机会估计不多,把握机会。或者说秋招时间去冲实习,春招冲offer,但是压力会比较大
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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