Domanda di colloquio di Deltax

Problem statement You are given a string 'STR' representing JSON object. Return an array of strings denoting JSON objects with proper indentation. Rules for proper indentation: 1. Every inner brace should increase one indentation to the following lines. 2. Every close brace should decrease one indentation to the same line and the following lines. 3. Every ‘,’ will mean a separate line. 4. The indents can be increased with an additional 4 spaces or ‘/t’. Example: Let the input be: "{A:"B",C:{D:"E",F:{G:"H",I:"J"}}}" Then we return the following array of strings: { A:"B", C: { D:"E", F: { G:"H", I:"J" } } } Note that for every new brace we are putting an additional 4 spaces or \t. Note: 1. [] and {} are only acceptable braces in this case.

Risposta di colloquio

Anonimo

8 gen 2024

#include vector prettyJSON(string &str) { // Write your code here. auto r = 0; vector result(1, ""); int brace = 1; for (auto i = 0; i < str.length(); ++i) { switch (str[i]) { // Space just ignore. case ' ': continue; case '{': case '[': // If first brace. if (brace == 1 && r == 0) result[r] += str[i]; else { // Make a new line and add adequate spaces and increment braces. result.push_back(""); result[++r] += string(brace, '\t'); result[r] += str[i]; ++brace; } result.push_back(""); result[++r] += string(brace, '\t'); break; case '}': case ']': // Make a new line and decrement braces. if (brace > 1) { result.push_back(""); result[++r] += string(brace - 1, '\t'); result[r] += str[i]; --brace; } else { result.push_back(""); result[++r] += str[i]; --brace; } break; case ',': result[r] += str[i]; // Corner case check. if (str[i + 1] == '{' || str[i + 1] == '[') continue; else { result.push_back(""); result[++r] += string(brace, '\t'); } break; case ':': result[r] += str[i]; if (str[i + 1] == '{' || str[i + 1] == '[') { result.push_back(""); result[++r] += string(brace, '\t'); result[r] += str[++i]; ++brace; if (str[i + 1] != '{' && str[i + 1] != '[') { result.push_back(""); result[++r] += string(brace, '\t'); result[r] += str[++i]; } } break; default: // For all other cases. result[r] += str[i]; break; } } return result; }

1