July 16, 2022

1166. Design File System

1166. Design File System

Sol 1. HashMap

class FileSystem {
    
    Map<String, Integer> map;

    public FileSystem() {
        map = new HashMap<>();
    }
    
    public boolean createPath(String path, int value) {
        if (path.isEmpty() || path.equals("/") || map.containsKey(path)) {
            return false;
        }
        int delimIndex = path.lastIndexOf("/");
        String parent = path.substring(0, delimIndex);
        if (parent.length() > 1 && !map.containsKey(parent)) {
            return false;
        }
        map.put(path, value);
        return true;
    }
    
    public int get(String path) {
        return map.getOrDefault(path, -1);
    }
}

/**
 * Your FileSystem object will be instantiated and called as such:
 * FileSystem obj = new FileSystem();
 * boolean param_1 = obj.createPath(path,value);
 * int param_2 = obj.get(path);
 */

Sol 2. Trie

class FileSystem {
    
    class TrieNode {
        String name;
        int val;
        Map<String, TrieNode> map;
        
        TrieNode (String name) {
            this.name = name;
            this.val = -1;
            map = new HashMap<>();
        }
    }
    
    TrieNode root;

    public FileSystem() {
        this.root = new TrieNode("");
    }
    
    public boolean createPath(String path, int value) {
        String[] components = path.split("/");
        TrieNode cur = root;
        for (int i = 1; i < components.length; i++) {
            String curComponent = components[i];
            if (!cur.map.containsKey(curComponent)) {
                if (i == components.length - 1) {
                    cur.map.put(curComponent, new TrieNode(curComponent));
                } else {
                    return false;
                }
            }
            cur = cur.map.get(curComponent);
        }
        if (cur.val != -1) {
            return false;
        }
        cur.val = value;
        return true;
    }
    
    public int get(String path) {
        String[] components = path.split("/");
        TrieNode cur = root;
        for (int i = 1; i < components.length; i++) {
            String curComponent = components[i];
            if (!cur.map.containsKey(curComponent)) {
                return -1;
            }
            cur = cur.map.get(curComponent);
        }
        return cur.val;
    }
}

/**
 * Your FileSystem object will be instantiated and called as such:
 * FileSystem obj = new FileSystem();
 * boolean param_1 = obj.createPath(path,value);
 * int param_2 = obj.get(path);
 */
comments powered by Disqus