We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
// simple annotated solution#include<vector>#include<iostream>#include<unordered_map>usingnamespacestd;intmain(){// handle inputintn,q;cin>>n>>q;cin.ignore();// need this after cin and before getlinevector<string>hrml;vector<string>queries;for(inti=0;i<n;i++){stringline;getline(cin,line);hrml.push_back(line);}for(inti=0;i<q;i++){stringline;getline(cin,line);queries.push_back(line);}// tokenise hrmlunordered_map<string,string>values;// the map we will query latervector<string>scope={};// current scope e.g. {"tag1", "tag2"}for(inti=0;i<hrml.size();i++){stringtag="";// strip quotes, also <> since newline already delimits new tagsfor(intj=0;j<hrml[i].size();j++){if(hrml[i][j]!='\"'&&hrml[i][j]!='<'&&hrml[i][j]!='>'){tag+=hrml[i][j];}}// return to prev scope if tag has been closedif(tag[0]=='/'){scope.pop_back();}else{// split line into tokensvector<string>tokens={};stringtoken="";for(intj=0;j<tag.size();j++){if(tag[j]!=' '){token+=tag[j];}else{// done with current tokentokens.push_back(token);token="";}}// last token is not followed by a space so we push it hereif(token.size())tokens.push_back(token);// parse tokens// first token is always innermost scopescope.push_back(tokens[0]);for(intj=1;j<tokens.size()-1;j++){// we look for pattern "*", "=", "*" in tokensif(tokens[j+1]=="="){// start with outermost scopestringkey=scope[0];for(intk=1;k<scope.size();k++){// append additional scope tags with dotkey+="."+scope[k];}// finally add attribute namekey+="~"+tokens[j];values[key]=tokens[j+2];// if we have found a valid attribute=value pattern skip next 2+1 casesj+=2;}}}}// handle queriesfor(inti=0;i<q;i++){if(values.find(queries[i])==values.end()){// if can't find query in valuescout<<"Not Found!"<<endl;}else{cout<<values[queries[i]]<<endl;}}return0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Attribute Parser
You are viewing a single comment's thread. Return to all comments →