题解 | #查找兄弟单词#

查找兄弟单词

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

import java.util.*;

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

        // 思路:先查找到单词的兄弟单词,然后进行排序,比较是否是兄弟单词的时候,不仅要比较是否包含截取出来的字符,而且需要数量相同。

        // 先收集输入
        String str = in.nextLine();
        String[] strArr = str.split(" ");

        // 初始化两个HashMap用来存放单词进行比较
        TreeMap<Character,Integer> temp1 = new TreeMap<>();
        TreeMap<Character,Integer> temp2 = new TreeMap<>();

        for (char s : strArr[strArr.length -2].toCharArray()) {
            temp2.put(s,temp2.getOrDefault(s,1)+1);
        }

        // 初始化一个数组用来存放兄弟单词
        ArrayList<String> temp3 = new ArrayList<>();
        for (int i = 1; i < strArr.length - 1 ; i++) {
            if (!strArr[i].equals(strArr[strArr.length - 2])) {
                for (char s : strArr[i].toCharArray()) {
                    temp1.put(s,temp1.getOrDefault(s,1)+1);
                }
                if (temp2.equals(temp1)) {
                    temp3.add(strArr[i]);
                }
                temp1.clear();
            }   
        }


        // 对temp3进行排序
        Collections.sort(temp3);

        System.out.println(temp3.size());
        if (Integer.valueOf(strArr[strArr.length - 1]) < temp3.size()) {
            System.out.print(temp3.get(Integer.valueOf(strArr[strArr.length - 1]) - 1));
        }
        
    }
}

全部评论

相关推荐

fRank1e:吓得我不敢去外包了,但是目前也只有外包这一个实习,我还要继续去吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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