โจทย์
The singleton pattern makes sure a class has exactly one instance that everyone shares, a common choice for application settings.
จำลองการกำหนดค่าแบบแชร์หนึ่งชุดที่เริ่มต้นว่างเปล่า ประมวลผลคำสั่งตามลำดับ:
set <key> <value>: store the value for the key (replacing any old value).get <key>: read the key's current value, ormissingif 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).
อินพุต
operations: Strings in the two forms above. Keys and values contain no spaces.
เอาต์พุต
Return the results of the get operations, in order.
เงื่อนไข
1 ≤ จำนวนคำสั่ง ≤ 10,000
คีย์และค่ายาว 1 ถึง 20 อักขระ
ตัวอย่าง
อินพุต:
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 ถูกตั้งเป็น dark ส่วน language ไม่เคยตั้ง จึงเป็น missing: ["dark", "missing"]
อินพุต:
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"};
คำอธิบาย
set ครั้งที่สองแทนค่าเดิมในอินสแตนซ์ที่ใช้ร่วมกันตัวเดียวกัน: ["vi"]
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
ทุกคำสั่งอ่านและเขียนออบเจกต์เดียวกัน
คำใบ้ 2
dictionary จากคีย์ไปค่าก็พอสำหรับเก็บการตั้งค่า
คำใบ้ 3
คีย์ที่ไม่เคยถูกตั้งต้องคืนข้อความ missing
ความซับซ้อนที่คาดหวัง
เวลา O(จำนวนคำสั่ง), หน่วยความจำเพิ่ม O(จำนวนคีย์)
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน