Dễ 0 đã giải Tỷ lệ chấp nhận 0%

One Shared Configuration

Simulate a singleton settings object: every part of the program reads and writes the same instance.

Bạn sẽ học được gì

  • Share one object across the whole program
  • Create an instance lazily on first use
  • Read and update settings through one place

Đề bài

Xem bản dịch

The singleton pattern makes sure a class has exactly one instance that everyone shares, a common choice for application settings.

Simulate one shared configuration that starts empty. Process the operations in order:

  • set <key> <value>: store the value for the key (replacing any old value).
  • get <key>: read the key's current value, or missing if it was never set.

Because every caller uses the same instance, a value set by one operation is visible to every later get.

Implement shared_configuration(operations).

Input

operations: Strings in the two forms above. Keys and values contain no spaces.

Output

Return the results of the get operations, in order.

Ràng buộc

1 ≤ number of operations ≤ 10,000

Keys and values have 1 to 20 characters

Ví dụ

Ví dụ 1
Đầu vào:
operations = ["set theme dark", "get theme", "get language"]

Kết quả mong đợi:
expected = ["dark", "missing"]
Đầu vào:
std::vector<std::string> operations = {"set theme dark", "get theme", "get language"};

Kết quả mong đợi:
std::vector<std::string> expected = {"dark", "missing"};
Đầu vào:
string[] operations = new string[] {"set theme dark", "get theme", "get language"};

Kết quả mong đợi:
string[] expected = new string[] {"dark", "missing"};

Giải thích

theme was set to dark; language was never set, so it is missing: ["dark", "missing"].

Ví dụ 2
Đầu vào:
operations = ["set lang en", "set lang vi", "get lang"]

Kết quả mong đợi:
expected = ["vi"]
Đầu vào:
std::vector<std::string> operations = {"set lang en", "set lang vi", "get lang"};

Kết quả mong đợi:
std::vector<std::string> expected = {"vi"};
Đầu vào:
string[] operations = new string[] {"set lang en", "set lang vi", "get lang"};

Kết quả mong đợi:
string[] expected = new string[] {"vi"};

Giải thích

The second set replaces the first value in the same shared instance: ["vi"].

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

All operations read and write the same single object.

Gợi ý 2

A dictionary from key to value is enough to hold the settings.

Gợi ý 3

A key that was never set must return the text missing.

Độ phức tạp mong đợi

O(number of operations) time, O(number of keys) extra space

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.