有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在JAVA中查找JSON字符串深度的数组

java方法中给了我一个字符串,我必须返回该字符串的子深度

比如如果方法是

find depthJSON(String s){
     //code
     return count;
}

例如:

{
    "0" : { "name" : "John", "City" : "NY"},
    "1" : { "name" : "Mike", "City" : "LA"}
}

对于该输入,深度为2


共 (1) 个答案

  1. # 1 楼答案

    我的答案是

        int JsonDepth (String S) { 
            int current_max = 0; 
            int max = 0; 
            int n = S.length(); 
    
            for (int i = 0; i < n; i++) { 
                if (S.charAt(i) == '{') { 
                    current_max++; 
    
                    // update max if required 
                    if (current_max > max) { 
                        max = current_max; 
                    } 
                } else if (S.charAt(i) == '}') { 
                    if (current_max > 0) { 
                        current_max ; 
                    } else { 
                        return -1; 
                    } 
                } 
            } 
    
            if (current_max != 0) { 
                return -1; 
            } 
    
            return max; 
        }