-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0588-DesignInMemoryFileSystem.cs
104 lines (82 loc) · 2.78 KB
/
0588-DesignInMemoryFileSystem.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
//-----------------------------------------------------------------------------
// Runtime: 300ms
// Memory Usage: 34.9 MB
// Link: https://leetcode.com/submissions/detail/365341536/
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace LeetCode
{
public class _0588_DesignInMemoryFileSystem
{
private readonly FileNode root;
public _0588_DesignInMemoryFileSystem()
{
root = new FileNode("");
}
public IList<string> Ls(string path)
{
return FindNode(path).GetList();
}
public void Mkdir(string path)
{
FindNode(path);
}
public void AddContentToFile(string filePath, string content)
{
FindNode(filePath).AddContent(content);
}
public string ReadContentFromFile(string filePath)
{
return FindNode(filePath).Content;
}
private FileNode FindNode(string path)
{
var levels = path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
var curr = root;
foreach (var level in levels)
{
if (level.Length == 0) continue;
if (!curr.Children.ContainsKey(level))
curr.Children[level] = new FileNode(level);
curr = curr.Children[level];
if (curr.IsFile) break;
}
return curr;
}
private class FileNode
{
private readonly SortedDictionary<string, FileNode> children;
private readonly StringBuilder file;
public FileNode(string name)
{
children = new SortedDictionary<string, FileNode>();
file = new StringBuilder();
Name = name;
}
public string Name { get; }
public IDictionary<string, FileNode> Children => children;
public string Content => file.ToString();
public void AddContent(string content) => file.Append(content);
public bool IsFile => file.Length > 0;
public List<string> GetList()
{
var list = new List<string>(); ;
if (IsFile)
list.Add(Name);
else
list.AddRange(children.Keys);
return list;
}
}
}
/**
* Your FileSystem object will be instantiated and called as such:
* FileSystem obj = new FileSystem();
* IList<string> param_1 = obj.Ls(path);
* obj.Mkdir(path);
* obj.AddContentToFile(filePath,content);
* string param_4 = obj.ReadContentFromFile(filePath);
*/
}