又是一道需要递归处理的题目,把JSON看做一个对象,process用于递归处理一个对象
本题需注意的细节
- 永远卡掉遇到的第一个反斜
- 特殊判断 { } 的情况
- 不能以" " 作为收集字符串的终点,有时候""也会作为内容
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
public class JSON查询 {
static Map<String,String> map = new HashMap<>();
static int len,i= 0;
static StringBuilder x;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String[] one = br.readLine().split(" ");
int n = Integer.parseInt(one[0]);
int m = Integer.parseInt(one[1]);
String r = null;
x = new StringBuilder("");
while(n-->0) {
r = br.readLine();
x.append(r);
}
len = x.length();
process("");
while(m-->0) {
String q = br.readLine();
String s = map.get("."+q);//全加上点,方便处理
if(s==null) {
bw.write("NOTEXIST\n");
}else if(s.equals("OBJECT")) {
bw.write(s+"\n");
}else {
bw.write("STRING "+s+"\n");
}
}
bw.flush();
}
private static String[] process(String key) {
while(true) {
int cn[] = checkNull();//判断特殊情况,不判断为90分
if(cn[0]==1) {
i = cn[1];//把i放在 } 位置,然后break
break;
}
String i_key[] = getKey();
i = Integer.parseInt(i_key[0])+1;//i停在冒号,加一卡掉冒号
String kt = key+"."+i_key[1];
String[] i_v = getValue(kt);
map.put(kt, i_v[1]);//存
i = Integer.parseInt(i_v[0]);
if(x.charAt(i)=='}')break;//收完值,i只能停在 } 或 ,
else i++;//收集完了一项,加一卡掉逗号
}
return new String[] {String.valueOf(i+1),"OBJECT"};//相当于收集完了一项,加一卡掉逗号
}
private static String[] getKey() {
while(x.charAt(i)=='{'||x.charAt(i)==' ')i++;
StringBuilder res = new StringBuilder("");
getContent(res);
while(x.charAt(i)!=':')i++;//停在冒号
return new String[] {String.valueOf(i),res.toString()};//返回寻找value的起始位置和Key
}
private static String[] getValue(String key) {
while(x.charAt(i)==' ')i++;
if(x.charAt(i)=='"') {//值是字符串
StringBuilder res = new StringBuilder("");
getContent(res);
while(x.charAt(i)!=','&&x.charAt(i)!='}') i++;
return new String[] {String.valueOf(i),res.toString()};
}else
return process(key);
}
private static int[] checkNull() {
int j = i+1;
while(x.charAt(j)==' ') j++;
if(x.charAt(j)=='}') return new int[] {1,j};
return new int[] {0,0};
}
private static void getContent(StringBuilder res) {
i++;//卡掉引号
boolean F = true;
while(x.charAt(i+1)!=' '&&x.charAt(i+1)!=':'&&x.charAt(i+1)!='}'&&x.charAt(i+1)!=',') {
if(x.charAt(i)=='\\'&&F) {//永远卡掉第一个反斜
F = false;
}else {
res.append(x.charAt(i));
F = true;
}
i++;
}
}
}
网友评论