Problema
JSON is the text format most programs use to exchange data. A JSON object is written as {"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).
Input
keys, values: Lists of the same length.
Output
Return the JSON text. An empty object is {}.
Restricciones
0 ≤ number of pairs ≤ 100
Keys and values have at most 50 printable characters
Ejemplos
Entrada:
keys = ["name", "city"]
values = ["Ada", "London"]
Salida esperada:
expected = "{\"name\": \"Ada\", \"city\": \"London\"}"
Entrada:
std::vector<std::string> keys = {"name", "city"};
std::vector<std::string> values = {"Ada", "London"};
Salida esperada:
std::string expected = "{\"name\": \"Ada\", \"city\": \"London\"}";
Entrada:
string[] keys = new string[] {"name", "city"};
string[] values = new string[] {"Ada", "London"};
Salida esperada:
string expected = "{\"name\": \"Ada\", \"city\": \"London\"}";
Explicación
Each pair becomes "key": "value": {"name": "Ada", "city": "London"}.
Entrada:
keys = ["quote"]
values = ["say \"hi\""]
Salida esperada:
expected = "{\"quote\": \"say \\\"hi\\\"\"}"
Entrada:
std::vector<std::string> keys = {"quote"};
std::vector<std::string> values = {"say \"hi\""};
Salida esperada:
std::string expected = "{\"quote\": \"say \\\"hi\\\"\"}";
Entrada:
string[] keys = new string[] {"quote"};
string[] values = new string[] {"say \"hi\""};
Salida esperada:
string expected = "{\"quote\": \"say \\\"hi\\\"\"}";
Explicación
The quotes inside the value are escaped with a backslash: {"quote": "say \"hi\""}.
Cómo abordarlo
Inténtalo primero por tu cuenta y luego abre las pistas una a una.
Pista 1
Build each "key": "value" pair separately, then join them.
Pista 2
Escape backslashes before quotes so you don't escape your own escapes.
Pista 3
An empty input still needs the braces: {}.
Complejidad esperada
O(total length) time, O(total length) extra space
Referencias
Este reto está adaptado para CodeUtility. Sigue el enunciado y las restricciones indicadas arriba.