AcWing 3249. JSON查询
原题链接
中等
作者:
把这题Ac了
,
2024-12-01 19:56:15
,
所有人可见
,
阅读 2
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <map>
using namespace std;
struct Obj{
int type; //1为str 2为dict
string str;
Obj(){}
Obj(string t){
str = t;
type = 1;
}
map<string,Obj> kv;
};
string work_str(string &str,int &pos){
pos++; // '"'
string s;
while(pos < str.size() && str[pos] != '\"'){
if(str[pos] == '\\') s += str[pos + 1],pos += 2;
else s += str[pos++];
}
pos++; //过滤'"'
return s;
}
Obj work_obj(string &str,int &pos);
void work_kv(Obj &thisobj,string &str,int &pos){
string key = work_str(str,pos);
pos = str.find(':',pos);
while(str[pos] != '\"' && str[pos] != '{') pos++;
if(str[pos] == '\"') thisobj.kv[key] = Obj(work_str(str,pos));
else thisobj.kv[key] = work_obj(str,pos);
}
Obj work_obj(string &str,int &pos){
Obj thisobj;
thisobj.type = 2;
while(pos < str.size() && str[pos] != '{') pos++;
pos++;
while(pos < str.size() && str[pos] != '}'){
if(str[pos] == '\"') work_kv(thisobj,str,pos);
else pos++;
}
pos++;//过滤掉}
return thisobj;
}
void query(Obj obj,vector<string>& qs){
for(auto q : qs){
if(obj.type == 1 || !obj.kv.count(q)){
puts("NOTEXIST");
return ;
}
Obj t = obj.kv[q];
obj = t;
}
if(obj.type == 1) printf("STRING %s\n",obj.str.c_str());
else puts("OBJECT");
}
int main(){
int n,m;
cin >> n >> m;
getchar();
string str,s;
while(n--){
getline(cin,s);
str += s;
}
int p = 0;
auto mainobj = work_obj(str,p);
while(m--){
getline(cin,s);
vector<string> qs;
for(int i = 0;i < s.size();i++){
int j = i + 1;
while(j < s.size() && s[j] != '.') j++;
qs.push_back(s.substr(i,j - i));
i = j;
}
query(mainobj,qs);
}
return 0;
}