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.
#include<cmath>#include<cstdio>#include<vector>#include<map>#include<iostream>#include<algorithm>usingnamespacestd;voidltrim(string&s){s.erase(s.begin(),find_if(s.begin(),s.end(),[](unsignedcharch){return!isspace(ch);}));}voiddelete_quotes(string&s){if(s.size()>=2&&s.front()=='"'&&s.back()=='"'){s.erase(s.begin());s.pop_back();}}intmain(){intn,q;cin>>n>>q;vector<string>tag_stack;map<string,string>attrs;cin.ignore();for(inti=0;i<n;i++){stringline;getline(cin,line);if(line[1]!='/'){stringtag;size_tposition=1;// Start from position 1 to ignore the tag opening '<'// Capture the tag name:while(position<line.size()){// If a space or '>' is found, the tag name is completeif(line[position]==' '||line[position]=='>')break;tag+=line[position++];// The increment is performed after the character is added}tag_stack.push_back(tag);// Add the tag to the stackstringpath=tag_stack[0];// Create the tag path:for(intj=1;j<tag_stack.size();j++)path+=("."+tag_stack[j]);// Create a substring considering only the attributes and their valuesstringattributes=line.substr(position,line.length()-position-1);// Exclude the closing '>'ltrim(attributes);// Assign the attributes to the pathattrs[path]=attributes;}else{tag_stack.pop_back();}}for(inti=0;i<q;++i){stringquery;getline(cin,query);size_ttilde=query.find('~');stringpath=query.substr(0,tilde);stringattr=query.substr(tilde+1);if(attrs.count(path)){stringtag_attrs=attrs[path];size_tposition=tag_attrs.find(attr);if(tag_attrs.find(attr)!=string::npos&&(position==0||isspace(tag_attrs[position-1]))){stringvalue;position+=attr.length()+3;// Skip ' = '// Capture the value of the attribute:while(position<tag_attrs.length()&&tag_attrs[position]!=' ')value+=tag_attrs[position++];delete_quotes(value);cout<<value<<endl;}else{cout<<"Not Found!"<<endl;}}else{cout<<"Not Found!"<<endl;}}}
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 →
Probably no the best solution, but it works: