問 題 描述: |
問題描述 JSON (JavaScript Object Notation) 是一種輕量級的數據交換格式,可以用來描述半結構化的數據。JSON 格式中的基本單元是值 (value),出於簡化的目的本題只涉及 2 種類型的值: 輸入格式 第一行是兩個正整數 n 和 m,分別表示 JSON 數據的行數和查詢的個數。 輸出格式 對於輸入的每一個查詢,按順序輸出查詢結果,每個結果佔一行。 樣例輸入 10 5 樣例輸出 STRING John 評測用例規模與約定 n ≤ 100,每行不超過 80 個字符。 |
package jsonQuery;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
// 思路:將所有Json語句整合成一條字符串,並去除空格.使用數組來模擬棧結構,
// 每出現{數組下標遞增即爲壓棧,每出現}數組下標遞減,即爲彈棧,以此來判別層級
@SuppressWarnings({ "resource" })
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();// Json數據的行數
int m = sc.nextInt();// 待查詢key個數
StringBuilder JsonData = new StringBuilder();// 存儲所有Json語句
sc.nextLine();
for (int i = 0; i < n; i++)
JsonData.append(sc.nextLine().replace(" ", ""));// 去除所有空格方便進行操作
Map<String, String> nodes = new HashMap<String, String>();
String[] stack = new String[100];// 模擬棧
stack[0] = "rootNode";// 根節點
int level = 1;// 當前層級,初始值爲1
String[] result = new String[m];// 存儲輸出結果
String key = "null", value = "null";
boolean isKey = true;// 判斷下一引號內是否爲鍵值
for (int i = 1; i < JsonData.length(); i++) {
switch (JsonData.charAt(i)) {
case '"':
StringBuilder temp = new StringBuilder();// 暫時保存引號中的字符串
boolean flag = true;// 循環結束標記
while (flag) {
i++;
switch (JsonData.charAt(i)) {
case '\\':// 若爲轉義字符跳過此字符
i++;
temp.append(JsonData.charAt(i));
break;
case '"':// 若爲引號則此字符串結束
flag = false;
break;
default:
temp.append(JsonData.charAt(i));
break;
}
}
if (isKey) {
key = temp.toString();// 獲取鍵
if (level - 1 != 0)// 判斷前一層級是否存在
key = stack[level - 1] + "." + key;// 存在則加上前綴
} else {
value = temp.toString();// 獲取值
nodes.put(key, "STRING " + value);
}
break;
case '{':// 遇到{則對象爲鍵值對,層級上升
stack[level] = key;// 壓棧
nodes.put(key, "OBJECT");
level++;
isKey = true;
break;
case ',':
isKey = true;
break;// 下一字符串爲鍵
case '}':
level--;
break;
case ':':
isKey = false;
break;// 下一字符串爲值
}
}
for (int i = 0; i < m; i++)// 讀取查詢內容
{
String query = sc.nextLine();
if ((result[i] = nodes.get(query)) == null)// 判斷對應的鍵是否非空且存在
result[i] = "NOTEXIST";
}
for (String str : result)
System.out.println(str);
}
}