The only argument given is the integer array A.
Return a list of strings, where each entry corresponds to a single line. The strings should not have "\n" character in them.
Input 1:
A = "{A:"B",C:{D:"E",F:{G:"H",I:"J"}}}"
Output 1:
{
A:"B",
C:
{
D:"E",
F:
{
G:"H",
I:"J"
}
}
}
Input 2:
A = ["foo", {"bar":["baz",null,1.0,2]}]
Output 2:
[
"foo",
{
"bar":
[
"baz",
null,
1.0,
2
]
}
]
public class Solution {
public boolean isBracket(char c) {
if (c == '[' || c == '{' || c == '}' || c == ']')
return true;
else
return false;
}
public ArrayList<String> prettyJSON(String A) {
int tabLevel = 0;
ArrayList<String> ans = new ArrayList<>();
for (int i = 0; i < A.length();) {
if (A.charAt(i) == ' ')
i++;
StringBuilder tabs = new StringBuilder();
for (int j = 1; j <= tabLevel; j++)
tabs.append("\t");
if (isBracket(A.charAt(i))) {
String temp = tabs.toString() + A.charAt(i);
if (A.charAt(i) == '}' || A.charAt(i) == ']')
temp = temp.substring(1); // reduces 1 tab level in string
if (i + 1 < A.length() && A.charAt(i + 1) == ',') {
temp += A.charAt(i + 1);
i++;
}
ans.add(temp);
if (A.charAt(i) == '{' || A.charAt(i) == '[')
tabLevel++;
else
tabLevel--;
i++;
} else {
int temp = i;
StringBuilder str = new StringBuilder();
while (temp < A.length() && !isBracket(A.charAt(temp))) {
str.append(A.charAt(temp));
if (A.charAt(temp) == ',') {
temp++;
break;
}
temp++;
}
ans.add(tabs.toString() + str.toString());
i = temp;
}
}
return ans;
}
}