Java AC Solution


  • 0
    public class FileSystem {
    
        private Map<String, Set<String>> dirMap = new HashMap<>();
        private Map<String, String> contentMap = new HashMap<>();
        private Comparator<String> comparator = (a, b) -> { 
        	if (a.contains(b) && !a.equals(b)) return 1;
            if (b.contains(a) && !a.equals(b)) return -1;
            return a.compareTo (b);
        };
        
        public FileSystem() {
            dirMap.put ("/", new TreeSet<>(comparator));
        }
        
        public List<String> ls(String path) {
        	List<String> ans = new ArrayList<>();
        	if (contentMap.containsKey(path)) return Arrays.asList(path.substring(path.lastIndexOf("/") + 1));
        	for (String dir : dirMap.getOrDefault (path, new TreeSet<>(comparator))) 
        		ans.add(dir.substring(path.length() + (path.charAt(path.length() - 1) == '/' ? 0 : 1)));
        	return ans;
        }
        
        public void mkdir(String path) {
            String prev = "/";
            for (int idx = 1; idx <= path.length(); idx ++) {
                if (idx == path.length() || path.charAt (idx) == '/') {
                    String dir = path.substring (0, idx); 
                    dirMap.computeIfAbsent (prev, k -> new TreeSet<>(comparator)).add (dir);
                    prev = dir;
                }
            }
            dirMap.putIfAbsent (path, new TreeSet<>(comparator));
        }
        
        public void addContentToFile(String filePath, String content) {
        	mkdir(filePath);
            contentMap.put (filePath, contentMap.getOrDefault (filePath, "") + content);
        }
        
        public String readContentFromFile(String filePath) {
            return contentMap.getOrDefault (filePath, "");
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.