题解 | #查找兄弟单词#

查找兄弟单词

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        while (sc.hasNext()) {
            String[] str = new String[n];
            for (int i = 0 ; i < n; i++) {
                str[i] = sc.next();
            }
            String demo = sc.next();
            int index = sc.nextInt();

            Map<Character, Integer> map = new HashMap<>();
            //统计样本单词每个字母的数量
            for (char ch : demo.toCharArray()) {
                map.put(ch, map.getOrDefault(ch, 0) + 1);
            }
            List<String> resList = new ArrayList<>();
            for (String s : str) {
                if (s.equals(demo)) {
                    continue;
                }
                Map<Character, Integer> mapDeep = new HashMap<>();
                mapDeep.putAll(map);
                for (char ch2 : s.toCharArray()) {
                    if (mapDeep.containsKey(ch2)) {
                        //减小map中被用过单词的数量
                        mapDeep.put(ch2, mapDeep.get(ch2) - 1);
                    } else {
                        mapDeep.put(ch2, -1);
                    }
                }
                Collection<Integer> values = mapDeep.values();
                if (Collections.min(values) == 0 && Collections.max(values) == 0) {
                    resList.add(s);
                }
            }
            System.out.println(resList.size());
            Collections.sort(resList);
            if(index > resList.size()){
                System.out.println();
            }else{
                System.out.println(resList.get(index - 1));
            }
        }
    }
}

全部评论

相关推荐

Lorn的意义:1.你这根本就不会写简历呀,了解太少了 2.你这些项目经历感觉真的没啥亮点啊,描述的不行,重写书写一下让人看到核心,就继续海投 注意七八月份ofer还是比较多的,越往后机会越少,抓住时机,抓紧检查疏漏,加油查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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