File System
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 105 106 107 | #pragma once #include<iostream> #include<unordered_map> #include<string> #include<sstream> using namespace std; namespace airbnb { struct TrieNode { TrieNode() { this->value = -1; } unordered_map<string, TrieNode*> children; int value; }; class FileSystem { private: TrieNode *root; void deleteTrie(TrieNode *p) { for (auto& pchild : p->children) { deleteTrie(pchild.second); } delete p; } public: FileSystem() { root = new TrieNode(); } ~FileSystem() { deleteTrie(root); } void Create(string path, int value) { TrieNode *p = root; string dir = ""; string logStr = ""; stringstream sspath(path); while (getline(sspath, dir, '/')) { if (dir == "") { continue; } logStr.append("/" + dir); if (p->children.find(dir) == p->children.end()) { break; } p = p->children[dir]; } if (!sspath.eof()) { cout << "Create: Error because " << logStr << " does not exist" << endl; return; } p->children[dir] = new TrieNode(); p->children[dir]->value = value; cout << "create path: " << logStr << " successfully" << endl; } int Get(string path) { TrieNode* p = root; stringstream sspath(path); string dir = ""; while (getline(sspath, dir, '/')) { if (dir == "") { continue; } if (p->children.find(dir) == p->children.end()) { cout << "Get: Error. Path: " << path << " does not exist" << endl; return - 1; } p = p->children[dir]; } cout << "Get value: " << p->value << endl; return p->value; } void DoTest() { FileSystem fs; fs.Create("/a", 1); fs.Get("/a"); fs.Create("/a/b", 2); fs.Create("/c/d", 1); fs.Get("/c"); } }; } |
Comments
Post a Comment