CCF 201809-3 JSON查询
此题为文本处理问题,细节很多(需要处理转义字符等)。对输入进行预处理后进行键值对分离,结果put进hashMap中。难点在于如何进行嵌套查询,使用ArrayList作为栈,保证键值对的一一对应,处理完结果后将该前缀弹出栈。
上满分代码:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static HashMap<String,String> hashMap = new HashMap<>();
public static ArrayList<String> preList = new ArrayList<>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] input = scanner.nextLine().split(" ");
int n = Integer.parseInt(input[0]);
int m = Integer.parseInt(input[1]);
StringBuilder strBuidler = new StringBuilder();
for(int i=0 ; i<n ; i++) {
String line = scanner.nextLine().replace(" ", "");
strBuidler.append(line);
}
String temp = "";
preList.add(null);
for(int i=0 ; i<strBuidler.length() ; i++) {
char ch = strBuidler.charAt(i);
switch(ch) {
case'"':
i++;
while(strBuidler.charAt(i)!='"') {
if(strBuidler.charAt(i)=='\\')i++;
temp += strBuidler.charAt(i);
i++;
}
if(strBuidler.charAt(i+1)==':') {
if(preList.get(preList.size()-1)!=null) {
temp = preList.get(preList.size()-1)+"."+temp;
}
preList.add(temp);
temp = "";
}else {
hashMap.put(preList.get(preList.size()-1), temp);
preList.remove(preList.size()-1);
temp = "";
}
break;
case'{':
hashMap.put(preList.get(preList.size()-1), "OBJECT");
break;
case'}':
preList.remove(preList.size()-1);
break;
}
}
for(int i=0 ; i<m ; i++) {
String line = scanner.nextLine();
if(!hashMap.containsKey(line)) {
System.out.println("NOTEXIST");
}else if(hashMap.get(line)=="OBJECT") {
System.out.println("OBJECT");
}else {
System.out.println("STRING "+hashMap.get(line));
}
}
}
}