보통 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에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.