CLP_Core Java_E2 - Hands-on 2, JSON object Count, JSON Level Count

2. CLP_Core Java_E2 - Hands-on 2






JSON is a syntax for storing and exchanging data. 

JSON rules:

  • Data is separated by commas. Curly braces hold objects (name/value pairs), and square brackets hold arrays (values).
  • Values can be literals, objects, or arrays.
  • Data starts at level 1. 
  • If a level 1 key has an object as value, the keys in that object are at level 2.


Input Specification:
input1: Stringified JSON object.
 
Output Specification:
The function should return the deepest level contained in the JSON object.
 

Example
input1: {"0": { "name": "John"},"1":{"name":"micheal"}}
 
Output: 2
 
Explanation:

{
  "0": {
    "name": "John"
  },
  "1": {
    "name": "micheal"
  }
}


The maximum depth level is 2.


Solution:-> JSON Level Count

import java.io.*;
import java.util.*;

public class Main
{
 
  public static int levelCount(String word){
    int maxLevel=1;
    int curLevel=1;
    /*write your code here and return appropriate value*/
    char[] arr  = word.toCharArray();
    for (int i=0;i<arr.length;i++) {
        if(arr[i]=='{') {
            curLevel++;
            if (curLevel>maxLevel) {
                maxLevel++;
            }
        }
        else if (arr[i]=='}' ){
            curLevel--;
        }
    }
   
      return maxLevel;
  }
 
  public static void main(String[] args)
  {
//    String word="{\"0\":{\"name\":\"John\"},\"1\":{\"name\":\"micheal\"}}";
      String word="{\"0\":{\"name\":\"[John]\"}\",\"1\":{\"name\":\"[micheal]\"}}";
    System.out.println(levelCount(word));
  }
}




CLP_Core Java_E2 - Hands-on 1,  Number of  turns to get original word string, Two-person string manipulation

Comments