【华为OD】文件目录大小

一个文件目录的数据格式为:目录 id ,本目录中文件大小, ( 子目录 id 列表 ) 。其中目录 id
局唯一,取值范围 [1,200] ,本目录中文件大小范围 [1,1000] ,子目录 id 列表个数 [0,10]
例如: 1 20 (2,3 )表示目录 1 中文件总大小是 20 ,有两个子目录, id 分别是 2 3
现在输入一个文件系统中所有目录信息,以及待查询的目录 id ,返回这个目录和及该目
录所有子目录的大小之和。 输入描述:
第一行为两个数字 M N ,分别表示目录的个数和待查询的目录 id 1 <= M <=100, 1<= N
<=200
接下来 M 行,每行为 1 个目录的数据:目录 id 本目录中文件大小 ( 子目录 id 列表 ) ,子目录
列表中的子目录 id 以逗号分隔。
输出描述:
待查询目录及其子目录的大小之和
public class MLSize {
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        //总数
        int sum=in.nextInt();
        //待查询目录
        int target=in.nextInt();
        Map<Integer,Integer> sizeMap=new HashMap<>();
        Map<Integer,Integer[]> childMap=new HashMap<>();
        while (in.hasNext()){
            int index=in.nextInt();
            sizeMap.put(index,in.nextInt());
            String child=in.next();
            String s = child.replace("()","");
            //获取子文件目录
            if (isNoEmpty(s)){
                //对字符串进行处理
                String replace1 = s.replace("(", "");
                String replace2 = replace1.replace(")", "");
                String[] split = replace2.split(",");
                Integer[] childIndex=new Integer[split.length];
                for (int i=0;i<split.length;i++){
                    childIndex[i]=Integer.parseInt(split[i]);
                }
                //写入
                childMap.put(index,childIndex);
            }
        }
        int num=0;
        num = getSize(sizeMap, target, childMap);
        System.out.println(num);
    }

    /**
     * 判断字符串是否有值
     */
    public static boolean isNoEmpty(String s){
        return s != null && s.length() != 0;
    }


    /**
     * 获取对应index的文件目录数
     */
    public static int getSize(Map<Integer,Integer> sizeMap,int target,Map<Integer,Integer[]> childMap){
         int sum=sizeMap.get(target);
         if (childMap.get(target)!=null){
             Integer[] integers = childMap.get(target);
             for (Integer integer : integers) {
                 sum += getSize(sizeMap, integer, childMap);
             }
         }
         return sum;
    }

}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值