ปานกลาง 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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก