题解 | #查找兄弟单词#

查找兄弟单词

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));
        }
    }
}

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

相关推荐

像好涩一样好学:这公司我也拿过 基本明确周六加班 工资还凑活 另外下次镜头往上点儿
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务