मध्यम 0 हल किए गए 0% स्वीकृति

RAII Release Order

Work out the order in which scoped resources are released when their scopes end, as RAII guarantees.

आप क्या सीखेंगे

  • Release resources when a scope ends
  • Destroy objects in reverse creation order
  • Model nested scopes with a stack

समस्या

अनुवाद दिखाएँ

In C++, RAII ties a resource to an object's lifetime: the resource is released automatically when the object goes out of scope. Objects in the same scope are destroyed in reverse order of creation.

Process the events in order:

  • {: enter a new inner scope.
  • }: leave the current scope; every resource acquired in it is released, newest first.
  • acquire <name>: create a resource in the current scope.

When the events run out, the remaining open scopes end from the innermost to the outermost (the program's outer scope included), releasing their resources the same way.

Implement raii_release_order(events).

Input

events: The events. Braces are balanced or left open, never closed without being opened.

Output

Return the resource names in the order they are released.

सीमाएँ

0 ≤ number of events ≤ 100,000

Names have 1 to 20 characters without spaces

उदाहरण

उदाहरण 1
इनपुट:
events = ["acquire db", "{", "acquire file", "acquire lock", "}", "acquire log"]

अपेक्षित आउटपुट:
expected = ["lock", "file", "log", "db"]
इनपुट:
std::vector<std::string> events = {"acquire db", "{", "acquire file", "acquire lock", "}", "acquire log"};

अपेक्षित आउटपुट:
std::vector<std::string> expected = {"lock", "file", "log", "db"};
इनपुट:
string[] events = new string[] {"acquire db", "{", "acquire file", "acquire lock", "}", "acquire log"};

अपेक्षित आउटपुट:
string[] expected = new string[] {"lock", "file", "log", "db"};

व्याख्या

Leaving the inner scope releases lock then file (newest first). At the end the outer scope releases log then db: ["lock", "file", "log", "db"].

उदाहरण 2
इनपुट:
events = ["{", "acquire a", "{", "acquire b"]

अपेक्षित आउटपुट:
expected = ["b", "a"]
इनपुट:
std::vector<std::string> events = {"{", "acquire a", "{", "acquire b"};

अपेक्षित आउटपुट:
std::vector<std::string> expected = {"b", "a"};
इनपुट:
string[] events = new string[] {"{", "acquire a", "{", "acquire b"};

अपेक्षित आउटपुट:
string[] expected = new string[] {"b", "a"};

व्याख्या

Two scopes are still open at the end: the innermost releases b, then the next releases a: ["b", "a"].

कैसे हल करें

पहले खुद कोशिश करें, फिर एक-एक करके संकेत खोलें।

संकेत 1

Keep a stack of scopes, each holding its resources in order.

संकेत 2

Closing a scope releases its resources from newest to oldest.

संकेत 3

At the end, close every scope that is still open, innermost first.

अपेक्षित जटिलता

O(number of events) time, O(number of events) extra space

संदर्भ

यह चुनौती CodeUtility के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।

दूसरों से सीखें

समुदाय समाधान

अभी तक कोई प्रकाशित समाधान नहीं। पहला साझा करने के लिए इस चुनौती को हल करें।