코딩테스트/HackerRank
[HackerRank] Attribute Parser
쪼르뚜
2024. 9. 9. 03:11
728x90
반응형
🔗 문제 링크
https://www.hackerrank.com/challenges/attribute-parser/problem
Attribute Parser | HackerRank
Parse the values within various tags.
www.hackerrank.com
반응형
728x90
👩💻 코드
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <set>
#include <map>
using namespace std;
int main() {
int N;
int Q;
cin >> N >> Q;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
map<string, string> lines;
set<string> nestedTag;
string tag;
int tagSize;
for(int i=0; i<N; i++){
string line;
getline(cin, line);
if(line[1] == '/'){
nestedTag.insert(tag);
line.pop_back();
string currentTag = line.substr(2);
if(tag.find(currentTag) != string::npos){
tag = tag.erase(tag.find(currentTag), currentTag.size());
}
if(tag.find('.') != string::npos){
tag = tag.substr(0, tag.size()-1);
}
}else{
string currentTag;
if(line.find(' ') != string::npos){
currentTag = line.substr(1, line.find(' ') - 1);
string attributes = line.substr(line.find(' '), line.find('>')-line.find(' '));
attributes.erase(remove(attributes.begin(), attributes.end(), ' '), attributes.end());
lines.insert({currentTag, attributes});
}else{
currentTag = line.substr(1, line.find('>') - 1);
}
tagSize = currentTag.size();
if(tag == ""){
tag += currentTag;
}else{
tag += '.' + currentTag;
}
}
}
for(int i=0; i<Q; i++){
string query;
getline(cin, query);
string tag = query.substr(0, query.find('~'));
string name = query.substr(query.find('~')+1);
if(nestedTag.count(tag)){
if(tag.find('.') != string::npos){
tag = tag.substr(tag.rfind('.')+1);
}
bool isFind = false;
for(auto line : lines){
string currentTag = line.first;
string currentLine = line.second;
if(currentTag == tag && currentLine.find(name) != string::npos){
if((currentLine.find(name) == 0 || currentLine[currentLine.find(name)-1] == '"')
&& currentLine[currentLine.find(name) + name.size() + 1] == '"'){
string str1 = currentLine.substr(currentLine.find(name)+name.size()+2);
string str2 = str1.substr(0, str1.find('\"'));
cout << str2 << "\n";
isFind = true;
break;
}
}
}
if(!isFind){
cout << "Not Found!\n";
}
}else{
cout << "Not Found!\n";
}
}
return 0;
}
📝 풀이
HRML을 입력받을 때 시작하는 태그와 끝나는 태그를 구분합니다.
시작하는 태그라면 태그를 key값으로 속성들을 value값으로 lines에 추가합니다.
끝나는 태그라면 태그들의 종속관계에 맞춰 nestedTag에 추가합니다.
쿼리를 입력받을 때 태그와 속성 이름으로 나눕니다.
태그 이름이 nestedTag에 없다면 잘못된 태그이므로 'Not Found!'를 출력합니다.
태그 이름이 존재한다면 키로 검색 후 속성 이름이 존재하는지 확인합니다.
속성 이름이 존재한다면 속성 이름 중 일부인지 아닌지 확인합니다.
모든 조건을 만족한다면 제대로 찾은 것이기 때문에 출력합니다.
끝까지 조건을 만족하는 속성을 찾지 못 한다면 역시 'Not Found!'를 출력합니다.
728x90
반응형