Scribbling

[C++] Strings 본문

Computer Science/C++

[C++] Strings

focalpoint 2024. 9. 30. 11:59

https://www.hackerrank.com/challenges/attribute-parser/problem?isFullScreen=true

 

Attribute Parser | HackerRank

Parse the values within various tags.

www.hackerrank.com

 

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
#include <sstream>

using namespace std;


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int n, q;
    cin >> n >> q;
    cin.ignore();
    
    // tag1.tag2~attr : val
    map<string, string> parsed;
    string tags, attr;
    // parse n lines of hrml
    for (int i=0; i<n; i++) {
        string line;
        getline(cin, line);
        line = line.substr(1, line.size() - 2);
        // opening tag
        if (line[0] != '/') {
            stringstream ss(line);
            string tag;
            getline(ss, tag, ' ');
            if (tags.empty()) {
                tags = tag;
            }
            else {
                tags += "." + tag;
            }
            string word;
            while (getline(ss, word, ' ')) {
                if (word[0] == '=') {
                    continue;
                }
                // value
                else if (word[0] == '"') {
                    parsed[tags + "~" + attr] = word.substr(1, word.size()-2);
                }
                // attr
                else {
                    attr = word;
                }
            }            
        }
        // closing tag
        else {
            line = line.substr(1, line.size() - 1);
            string tag(line);
            int idx = tags.find("." + tag);
            if (idx != string::npos) {
                tags = tags.substr(0, idx);
            }
            else {
                tags = "";
            }
        }
    }
    
    // for (auto e : parsed) {
    //     cout << e.first << endl;
    //     cout << e.second << endl;
    // }
    
    // queries
    for (int i=0; i<q; i++) {
        string line;
        getline(cin, line);
        if (parsed.find(line) == parsed.end()) {
            cout << "Not Found!" << endl;
        }
        else {
            cout << parsed[line] << endl;
        }
    }
    
}

 

'Computer Science > C++' 카테고리의 다른 글

[C++] Interface  (0) 2024.10.02
[C++] Object Oriented Programming  (0) 2024.10.01
[C++] Abstract Class, Polymorphism  (0) 2024.09.28
[C++] Virtual Functions  (0) 2024.09.28
[C++] Regular Expression Matching  (0) 2024.09.26