ccf 201709-3 JSON查询

来源:互联网 发布:淘宝 绳子泳衣 编辑:程序博客网 时间:2024/06/05 08:56

要点:可将多行JSON存储在一个string中,可将”.”直接作为map的key的一部分(考试的时候卡在这里,以为要递归调用,还想着把key和value编号处理,想得很复杂),可使用stack处理对象前缀的增加和减少。

#include<iostream>#include<map>#include<string>#include<stack>#include<cstdio>using namespace std;void update_prefix(stack<string> &st, string &prefix){    stack<string> st2;    string str = "";    prefix = "";    if(st.empty()) {        return;    }    while(!st.empty()){        str = st.top();        st2.push(str);        st.pop();    }    while(!st2.empty()){        str = st2.top();        st2.pop();        st.push(str);        prefix += str+".";    }}int main() {    int n, m;    cin >> n >> m;    getchar();    string data = "";    for(int i = 0; i < n; i++) {        string line;        getline(cin,line);        data += line;    }    int len = data.length();    string key,value,prefix;    int quote_type = 3;                 //标记4种引号,分别为key左右两个,value左右两个    key = value = prefix = "";    stack<string> st;    map<string,string> valueMap;    map<string,string> isObject;    valueMap.clear();    isObject.clear();    for(int i = 0; i < len; i++) {        if(data[i]=='{') {            if(key!="") {//                isObject[key] = true;     //刚开始错写成这个,80分                isObject[prefix+key] = true;                st.push(key);                prefix += key+".";//                update_prefix(st,prefix);            }            quote_type = 3;                 //初始化引号类型,由于遇到引号会先加一,这里初始化为最后一种引号            key = value = "";        } else if(data[i]=='}') {            if(!st.empty()) {                st.pop();                update_prefix(st,prefix);            }        } else if(data[i]=='\"') {            quote_type = (quote_type+1)%4;            if(quote_type==3) {                valueMap[prefix+key] = value;                key = value = "";            }        } else {            if(data[i]=='\\') {                i++;            }            if(quote_type==0) {                key += data[i];            }else if(quote_type==2){                value += data[i];            }        }    }//for    string query;    for(int i = 0; i < m; i++) {        getline(cin, query);        if(valueMap.count(query)) {            cout << "STRING " << valueMap[query] << "\n";        } else if(isObject.count(query)){            cout << "OBJECT\n";        } else {            cout << "NOTEXIST\n";        }    }    return 0;}