美团9.3笔试字母树Java

public class CharacterTree{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int[] num = new int[n - 1];
        int[] ans = new int[n];
        ArrayList<Integer>[] nm = new ArrayList[n];
        for(int i = 0; i < n ;i++){
            nm[i] = new ArrayList<Integer>();
        }
        for (int i = 0; i < n - 1; i++) {
            num[i] = scanner.nextInt();
            nm[num[i] - 1].add(Integer.valueOf(i + 1));
        }
        scanner.nextLine();
        String string = scanner.nextLine();
        for (int i = 0; i < n; i++) {
            Queue<Integer> queue = new LinkedList<>();
            queue.add(i);
            Set<Character> set = new HashSet<>();
            int count = 0;
            while (!queue.isEmpty()){
                int top = queue.peek();
                queue.poll();
                if(!set.contains(string.charAt(top))){
                    count++;
                    set.add(string.charAt(top));
                }
                for (Integer j : nm[top]){
                    queue.add(j);
                }
            }
            ans[i] = count;
        }
        for (int i = 0; i < n; i++) {
            System.out.println(ans[i]);
        }
    }
}
#美团笔试#
全部评论
大佬,你这题全a了ma
点赞 回复 分享
发布于 2022-09-05 16:43 上海
hi~同学,秋招遇“寒气”,牛客送温暖啦!23届秋招笔面经有奖征集中,参与就得牛客会员7天免费体验,最高赢300元京东卡!戳我去看>>>https://www.nowcoder.com/link/zhengjipinglun
点赞 回复 分享
发布于 2022-09-05 12:38 北京
{"pureText":"","imgs":[{"alt":"discuss_166****548117.jpeg","height":1623,"localSrc":"content://media/external/images/media/138082","src":"https://uploadfiles.nowcoder.com/message_images/20220905/165664256_1662345547451/discuss_1662345548117.jpeg","width":960}]}
点赞 回复 分享
发布于 2022-09-05 10:39 北京

相关推荐

07-08 13:48
门头沟学院 C++
点赞 评论 收藏
分享
07-07 17:06
已编辑
深圳技术大学 golang
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 12:31
以前小时候我最痛恨出轨、偷情的人,无论男女,为什么会出轨?现在我成了自己最讨厌的人,没想到分享的东西在牛客会被这么多人看,大家的评价都很中肯,我也认同,想过一一回复,但我还是收声了,我想我应该说说这件事,这件事一直压在我心里,是个很大的心结,上面说了人为什么出轨,我大概能明白了。我们大一下半年开始恋爱,开始恋爱,我给出了我铭记3年的承诺,我对她好一辈子,我永远不会背叛,我责任心太重,我觉得跟了我,我就要照顾她一辈子,我们在一起3年我都没有碰过她,她说往东我就往东,她说什么我做什么,她要我干什么,我就干什么!在学校很美好,中途也出过一些小插曲,比如男闺蜜、男闺蜜2号等等等。但我都强迫她改掉了,我...
牛客刘北:两个缺爱的人是没有办法好好在一起的,但世界上哪有什么是非对错?你后悔你们在一起了,但是刚刚在一起的美好也是真的呀,因为其他人的出现,你开始想要了最开始的自己,你的确对不起自己,21岁的你望高物远,你完全可以不谈恋爱,去过你想要的生活,你向往自由,在一起之后,你要想的不是一个人,而是两个人,你不是变心了,就像你说的,你受够了,你不想包容了,冷静几天是你最优的选择,爱人先爱己。
社会教会你的第一课
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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