题解 | #查找兄弟单词#

查找兄弟单词

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);
        while (in.hasNext()) { // 注意 while 处理多个 case
            int wordCount = in.nextInt();

            List<String> wordList = new ArrayList<>(wordCount);

            for (int i = 0; i < wordCount; i++) {
                String word = in.next();
                wordList.add(word);
            }

            String target = in.next();
            int k = in.nextInt();

            findBrother(wordList, target, k);
        }
    }

    public static void findBrother(List<String> wordList, String target, int k) {
        List<String> res = new ArrayList<>();
        char[] chars = target.toCharArray();
        HashMap<Character, Integer> targetMap = new HashMap<>();
        for (char ch : chars) {
            Integer times = targetMap.getOrDefault(ch, 0);
            targetMap.put(ch, times + 1);
        }

        for (String word : wordList) {
            if (word.length() != target.length() || word.equals(target)) {
                continue;
            }

            char[] charArray = word.toCharArray();
            boolean isBrother = true;

            HashMap<Character, Integer> wordMap = new HashMap<>();
            for (char ch : charArray) {
                if (!targetMap.containsKey(ch)) {
                    isBrother = false;
                    break;
                }
                Integer times = wordMap.getOrDefault(ch, 0);
                wordMap.put(ch, times + 1);
            }

            if (isBrother) {
                for (Map.Entry<Character, Integer> entry : wordMap.entrySet()) {
                    Character key = entry.getKey();
                    Integer value = entry.getValue();
                    if (!targetMap.get(key).equals(value)) {
                        isBrother = false;
                        break;
                    }
                }
            }

            if (isBrother) {
                res.add(word);
            }
        }

        int m = res.size();
        System.out.println(m);
        Collections.sort(res);

        if (m > k) {
            System.out.println(res.get(k - 1));
        }
    }
}

#在找工作求抱抱#
全部评论

相关推荐

05-20 13:59
门头沟学院 Java
米黑子米黑子:你这个成绩不争取下保研?
点赞 评论 收藏
分享
05-12 11:09
已编辑
门头沟学院 后端
已注销:没必要放这么多专业技能的描述。这些应该是默认已会的,写这么多行感觉在凑内容。项目这块感觉再包装包装吧,换个名字,虽然大家的项目基本都是网上套壳的,但是你这也太明显了。放一个业务项目,再放一个技术项目。技术项目,例如中间件的一些扩展和尝试。
简历中的项目经历要怎么写
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 13:05
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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