其他分享
首页 > 其他分享> > LeetCode 1166. Design File System

LeetCode 1166. Design File System

作者:互联网

原题链接在这里:https://leetcode.com/problems/design-file-system/

题目:

You are asked to design a file system that allows you to create new paths and associate them with different values.

The format of a path is one or more concatenated strings of the form: / followed by one or more lowercase English letters. For example, "/leetcode" and "/leetcode/problems" are valid paths while an empty string "" and "/" are not.

Implement the FileSystem class:

Example 1:

Input: 
["FileSystem","createPath","get"]
[[],["/a",1],["/a"]]
Output: 
[null,true,1]
Explanation: 
FileSystem fileSystem = new FileSystem();

fileSystem.createPath("/a", 1); // return true
fileSystem.get("/a"); // return 1

Example 2:

Input: 
["FileSystem","createPath","createPath","get","createPath","get"]
[[],["/leet",1],["/leet/code",2],["/leet/code"],["/c/d",1],["/c"]]
Output: 
[null,true,true,2,false,-1]
Explanation: 
FileSystem fileSystem = new FileSystem();

fileSystem.createPath("/leet", 1); // return true
fileSystem.createPath("/leet/code", 2); // return true
fileSystem.get("/leet/code"); // return 2
fileSystem.createPath("/c/d", 1); // return false because the parent path "/c" doesn't exist.
fileSystem.get("/c"); // return -1 because this path doesn't exist. 

Constraints:

题解:

Main a map between path and value.

When createPath, get parent of path, if it doen't exist in the map, return false. 

Otherwise, map.putIfAbsent(path, value). if putIfAbsent doesn't return null, it means path already exists in the map, return false.

Get is to simply return the value from the map.

Time Complexity: craetePath, O(n). n = path.length. get, O(1).

Space: O(m*n). m = map.size(). n = path length.

AC Java:

 1 class FileSystem {
 2     Map<String, Integer> map;
 3     
 4     public FileSystem() {
 5         map = new HashMap<>();
 6         map.put("", -1);
 7     }
 8     
 9     public boolean createPath(String path, int value) {
10         int ind = path.lastIndexOf("/");
11         if(ind == -1){
12             return false;
13         }
14         
15         String parent = path.substring(0, ind);
16         if(!map.containsKey(parent)){
17             return false;
18         }
19         
20         return map.putIfAbsent(path, value) == null;
21     }
22     
23     public int get(String path) {
24         return map.getOrDefault(path, -1);
25     }
26 }
27 
28 /**
29  * Your FileSystem object will be instantiated and called as such:
30  * FileSystem obj = new FileSystem();
31  * boolean param_1 = obj.createPath(path,value);
32  * int param_2 = obj.get(path);
33  */

 

标签:map,1166,return,get,createPath,Design,FileSystem,path,LeetCode
来源: https://www.cnblogs.com/Dylan-Java-NYC/p/16632244.html