โจทย์
JSON คือรูปแบบข้อความที่โปรแกรมส่วนใหญ่ใช้แลกเปลี่ยนข้อมูล JSON object เขียนในรูปแบบ {"key": "value", ...}
Given matching lists of keys and values (all text), build the JSON object string in this exact format:
- Start with
{and end with}. - Write each pair as
"key": "value", in the given order, separated by,(comma and space). - Inside a string, write a backslash
\as\\and a double quote"as\". Other characters stay as they are.
Implement json_object_string(keys, values).
อินพุต
keys, values: Lists of the same length.
เอาต์พุต
Return the JSON text. An empty object is {}.
เงื่อนไข
0 ≤ จำนวนคู่ ≤ 100
คีย์และค่ายาวไม่เกิน 50 อักขระที่พิมพ์ได้
ตัวอย่าง
อินพุต:
keys = ["name", "city"]
values = ["Ada", "London"]
ผลลัพธ์ที่คาดหวัง:
expected = "{\"name\": \"Ada\", \"city\": \"London\"}"
อินพุต:
std::vector<std::string> keys = {"name", "city"};
std::vector<std::string> values = {"Ada", "London"};
ผลลัพธ์ที่คาดหวัง:
std::string expected = "{\"name\": \"Ada\", \"city\": \"London\"}";
อินพุต:
string[] keys = new string[] {"name", "city"};
string[] values = new string[] {"Ada", "London"};
ผลลัพธ์ที่คาดหวัง:
string expected = "{\"name\": \"Ada\", \"city\": \"London\"}";
คำอธิบาย
แต่ละคู่กลายเป็น "key": "value": {"name": "Ada", "city": "London"}
อินพุต:
keys = ["quote"]
values = ["say \"hi\""]
ผลลัพธ์ที่คาดหวัง:
expected = "{\"quote\": \"say \\\"hi\\\"\"}"
อินพุต:
std::vector<std::string> keys = {"quote"};
std::vector<std::string> values = {"say \"hi\""};
ผลลัพธ์ที่คาดหวัง:
std::string expected = "{\"quote\": \"say \\\"hi\\\"\"}";
อินพุต:
string[] keys = new string[] {"quote"};
string[] values = new string[] {"say \"hi\""};
ผลลัพธ์ที่คาดหวัง:
string expected = "{\"quote\": \"say \\\"hi\\\"\"}";
คำอธิบาย
เครื่องหมายคำพูดในค่าถูก escape ด้วยแบ็กสแลช: {"quote": "say \"hi\""}
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
สร้างคู่ "key": "value" ทีละคู่ แล้วค่อยต่อกัน
คำใบ้ 2
escape แบ็กสแลชก่อนเครื่องหมายคำพูด จะได้ไม่ escape ส่วนที่เพิ่งใส่ซ้ำ
คำใบ้ 3
อินพุตว่างก็ยังต้องมีวงเล็บปีกกา: {}
ความซับซ้อนที่คาดหวัง
เวลา O(ความยาวรวม), หน่วยความจำเพิ่ม O(ความยาวรวม)
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน