【Leetcode】1166. Design File System

题目地址:

https://leetcode.com/problems/design-file-system/description/

要求设计一个文件系统,可以实现如下操作:
1、给定一个路径 s s s和一个值,路径的格式与Linux里的路径一样,题目保证路径不空,不等于根目录,只含英文小写字母。如果该路径已经存在,或其父目录不存在,则返回false;否则创建这个目录,并返回true。
2、返回某个路径 s s s对应的值。

用哈希表即可。代码如下:

class FileSystem {
 public:
  unordered_map<string, int> mp;
  FileSystem() {}

  bool createPath(string path, int value) {
    if (mp.count(path)) return false;
    int idx = path.size() - 1;
    while (path[idx] != '/') idx--;
    string parent = path.substr(0, idx);
    if (idx && !mp.count(parent)) return false;
    mp[path] = value;
    return true;
  }

  int get(string path) {
    auto it = mp.find(path);
    return it == mp.end() ? -1 : it->second;
  }
};

每个操作时间复杂度 O ( l s ) O(l_s) O(ls),空间 O ( n ) O(n) O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值