โจทย์
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).
อินพุต
events: เหตุการณ์ต่าง ๆ วงเล็บปีกกาอาจสมดุลหรือเปิดค้างไว้ แต่จะไม่ปิดโดยไม่มีการเปิดมาก่อน
เอาต์พุต
Return the resource names in the order they are released.
เงื่อนไข
0 ≤ จำนวนอีเวนต์ ≤ 100,000
ชื่อยาว 1 ถึง 20 อักขระ ไม่มีช่องว่าง
ตัวอย่าง
อินพุต:
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"};
คำอธิบาย
การออกจากขอบเขตด้านในคืน lock แล้วตามด้วย file (ใหม่สุดก่อน) สุดท้ายขอบเขตนอกคืน log แล้วตามด้วย db: ["lock", "file", "log", "db"]
อินพุต:
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"};
คำอธิบาย
ตอนจบยังมีสองขอบเขตเปิดอยู่ ขอบเขตในสุดคืน b แล้วขอบเขตถัดไปคืน a: ["b", "a"]
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
เก็บสแตกของขอบเขต แต่ละขอบเขตบันทึกทรัพยากรตามลำดับ
คำใบ้ 2
การปิดขอบเขตจะคืนทรัพยากรจากใหม่สุดไปเก่าสุด
คำใบ้ 3
ตอนจบให้ปิดทุกขอบเขตที่ยังเปิดอยู่ จากในสุดออกมา
ความซับซ้อนที่คาดหวัง
เวลา O(จำนวนอีเวนต์), หน่วยความจำเพิ่ม O(จำนวนอีเวนต์)
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน