Current streak:
0 days
Longest streak:
2 days
Less
More
import java.util.* ;
import java.io.*;
public class Solution {
public static ArrayList<String> prettyJSON(String str) {
// Write your code here.
int bracketCount = 0;
int arrayCount = 0;
ArrayList<String> al = new ArrayList<>();
StringBuilder spaces = new StringBuilder();
// Stack<Character> st = new Stack<>();
for(int i = 0; i < str.length();i++)
{
char c = str.charAt(i);
if(c == '{' || c == '['){
StringBuilder files = new StringBuilder();
files.append(spaces).append(c);
al.add(files.toString());
// System.out.println(spaces.toString() + c);
spaces.append('\t');
}
else if(c == ']' || c=='}'){
spaces.deleteCharAt(spaces.length() - 1);
StringBuilder files = new StringBuilder();
files.append(spaces).append(c);
// System.out.println(spaces.toString() + "sddasd");
if((i + 1) < str.length()){
if(str.charAt(i + 1) == ','){
files.append(",");
al.add(files.toString());
i++;
continue;
}
}
// System.out.println(spaces.toString() + c);
al.add(spaces.toString() + c);
}else{
StringBuilder st = new StringBuilder();
while( (c != '}' && c!= ']' && c !='{' && c!='[')){
st.append(c);
i++;
if(i<str.length()){
c = str.charAt(i);
}else{
break;
}
}
// System.out.println(st.toString());
if(c == '}' || c == ']' || c =='{' || c =='[')
{
// System.out.println(st.toString());
i--;
// st.deleteCharAt(st.length() - 1);
}
// String sx="";
// System.out.println(st.toString());
String []arr =st.toString().split(",");
if(arr.length == 1 && st.charAt(st.length() - 1) == ','){
String sx= (spaces.toString() + arr[0] + ",");
al.add(sx);
continue;
}
// System.out.println(Arrays.toString(arr));
for (int j = 0; j < arr.length; j++) {
if(j!=arr.length - 1){
String sx= (spaces.toString() + arr[j] + ",");
al.add(sx);
}else{
String sx= (spaces.toString() + arr[j]);
al.add(sx);
}
}
}
}
return al;
}
}