簡単 0件解決済み 正答率0%

One Shared Configuration

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

このチャレンジで学べること

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

問題

翻訳を表示

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.

制約

1 ≤ number of operations ≤ 10,000

Keys and values have 1 to 20 characters

例

例 1
入力:
operations = ["set theme dark", "get theme", "get language"]

期待される出力:
expected = ["dark", "missing"]
入力:
std::vector<std::string> operations = {"set theme dark", "get theme", "get language"};

期待される出力:
std::vector<std::string> expected = {"dark", "missing"};
入力:
string[] operations = new string[] {"set theme dark", "get theme", "get language"};

期待される出力:
string[] expected = new string[] {"dark", "missing"};

解説

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

例 2
入力:
operations = ["set lang en", "set lang vi", "get lang"]

期待される出力:
expected = ["vi"]
入力:
std::vector<std::string> operations = {"set lang en", "set lang vi", "get lang"};

期待される出力:
std::vector<std::string> expected = {"vi"};
入力:
string[] operations = new string[] {"set lang en", "set lang vi", "get lang"};

期待される出力:
string[] expected = new string[] {"vi"};

解説

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

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

All operations read and write the same single object.

ヒント 2

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

ヒント 3

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

目安の計算量

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

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。