[InterviewBit] Pretty Json

Pretty Json

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
void helper(string s, int& p, int tab, vector<string>& res) {
string tb = string(tab,'\t');
string now = "";
while(p < s.length() and (s[p] != '}' or s[p] != ']')) {
if(s[p] == '}') break;
if(s[p] == ']') break;
if(s[p] == '{') {
if(now.length()) {
res.push_back(tb + now);
now = "";
}
res.push_back(tb + "{");
helper(s,++p,tab+1,res);
res.push_back(tb + "}");
++p;
if(s[p] == ',') res.back().push_back(s[p++]);
} else if(s[p] == '[') {
if(now.length()) {
res.push_back(tb + now);
now = "";
}
res.push_back(tb + "[");
helper(s,++p,tab+1,res);
res.push_back(tb + "]");
++p;
if(s[p] == ',') res.back().push_back(s[p++]);
} else {
now.push_back(s[p]);
if(s[p] == ',') {
res.push_back(tb + now);
now = "";
}
++p;
}
}
if(now.length()) res.push_back(tb + now);
}
vector<string> Solution::prettyJSON(string A) {
vector<string> res;
int p = 0;
helper(A,p,0,res);
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/29/PS/interviewbit/pretty-json/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.