題目見https://blog.csdn.net/sinat_33431419/article/details/79433299
一開始想寫狀態機的,後來用了正則,搜了一個表達式來完成想要的功能:提取不在括號內的字符 譬如不在話括號內的",”逗號
,(?![^{]*})
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
class Node{
private String value;
private HashMap<String,Node> children = null;
Node(String inputText){
inputText = inputText.trim();
if(inputText.charAt(0)=='"'){
this.value = parse(inputText);
}else if (inputText.charAt(0)=='{'){
String trimed = inputText.substring(1,inputText.length()-1);
this.children = new HashMap<>();
for (String s:
trimed.split(",(?![^{]*})")) {
String[] ss = s.split(":(?![^{]*})");
assert (ss.length==2);
String name = ss[0].trim();
name = name.substring(1,name.length()-1);
children.put(name,new Node(ss[1]));
}
}else {
System.out.println("????");
}
}
private static String parse(String s){
char[] cs = s.toCharArray();
boolean f,in;
in = f = false;
StringBuilder sb = new StringBuilder();
for (char c :
cs) {
if (!in){
if (c=='"'){
in = true;
}
}else {
if(f){
assert ((c=='\\')||(c=='"'));
sb.append(c);
f = false;
}else {
if (c=='\\'){
f = true;
}else if (c=='"'){
break;
} else{
sb.append(c);
}
}
}
}
return sb.toString();
}
String find(String q){
q = q.trim();
int idx = q.indexOf('.');
if(idx==-1){
Node n = this.children.get(q);
if(n==null){
return "NOTEXIST";
}
if (n.children!=null){
return "OBJECT";
}else {
return "STRING "+n.value;
}
}else {
Node n = this.children.get(q.substring(0,idx));
return n.find(q.substring(idx+1));
}
}
}
public class A {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// 給出一個 JSON 格式描述的數據,以及若干查詢,編程返回這些查詢的結果。
// 輸入格式
// 第一行是兩個正整數 n 和 m,分別表示 JSON 數據的行數和查詢的個數。
// 接下來 n 行,描述一個 JSON 數據,保證輸入是一個合法的 JSON 對象。
// 接下來 m 行,每行描述一個查詢。給出要查詢的屬性名,要求返回對應屬性的內容。需要支持多層查詢,各層的屬性名之間用小數點 . 連接。保證查詢的格式都是合法的。
// 輸出格式
// 對於輸入的每一個查詢,按順序輸出查詢結果,每個結果佔一行。
// 如果查詢結果是一個字符串,則輸出 STRING ,其中 是字符串的值,中間用一個空格分隔。
// 如果查詢結果是一個對象,則輸出 OBJECT,不需要輸出對象的內容。
// 如果查詢結果不存在,則輸出 NOTEXIST。
String line = reader.readLine();
String[] a = line.split(" ");
int n = Integer.valueOf(a[0]);
int m = Integer.valueOf(a[1]);
StringBuilder stringBuffer = new StringBuilder();
for (int i = 0; i < n; i++) {
stringBuffer.append(reader.readLine());
}
String s = stringBuffer.toString();
s = s.replaceAll("“","\"");
s = s.replaceAll("”","\"");
Node root = new Node(s);
for (int i = 0; i < m; i++) {
System.out.println(root.find(reader.readLine()));
}
}
}