In this HackerEarth Alice's library problem solution Alice is rearranging her library. She takes the innermost shelf and reverses the order of books. She breaks the walls of the shelf. In the end, there will be only books and no shelf walls. Print the order of books.

Opening and closing walls of shelves are shown by '/' and '\' respectively whereas books are represented by lower case alphabets.


HackerEarth Alice's library problem solution


HackerEarth Alice's library problem solution.

#include <bits/stdc++.h>
using namespace std;

int main() {
    string s;
    cin >> s;
    
    stack<string> st;
    string curr_s = "";
    for(int i = 0; i < (int)s.size(); i++) {
        if(s[i] == '/') {
            st.push(curr_s);
            curr_s = "";
        } else if(s[i] == '\\') {
            reverse(curr_s.begin(), curr_s.end());
            string top = st.top();
            st.pop();
            top.append(curr_s);
            curr_s = top;
        } else {
            curr_s.push_back(s[i]);
        }
    }
    cout <<  curr_s << endl;

    return 0;
}

#include <bits/stdc++.h>
using namespace std;

#define CHAR 0
#define PTR 1

struct node {
    vector<int> type;
    vector<node*> childs;
    vector<char> chars;
    int size = 0;
    node() {}
};

struct node* parse(string& s, int start) {
    node *nd = new node();
    node *ch;
    for (int i = start; i < (int)s.size(); i++) {
        if (s[i] == '/') {
            nd->size += 1;
            nd->type.push_back(PTR);
            nd->childs.push_back(ch = parse(s, i+1));
            nd->chars.push_back(' ');
            i += ch->size;
            nd->size += ch->size;
        } else if (s[i] == '\\') {
            nd->size += 1;
            return nd;
        } else {
            nd->size += 1;
            nd->type.push_back(CHAR);
            nd->chars.push_back(s[i]);
            nd->childs.push_back(NULL);
        }
    }
}

string ans(node* t, int d) {
    string s = "";
    if (d%2 == 0) {
        for (int i = 0; i < (int)t->type.size(); i++) {
            if (t->type[i] == PTR) {
                s += ans(t->childs[i], d+1);
            } else {
                s += t->chars[i];
            }
        }
    } else {
        for (int i = (int)t->type.size()-1; i >= 0; i--) {
            if (t->type[i] == PTR) {
                s += ans(t->childs[i], d+1);
            } else {
                s += t->chars[i];
            }
        }

    }
    return s;
}

int main() {
    string s;
    cin >> s;
    node* nd = parse(s, 1);
    cout << ans(nd, 1) << endl;
    return 0;
}

Second solution

s = list(input())
opening = []
for i in range(len(s)):
    if s[i] == '/':
        opening += [i]
    elif s[i] == '\\':
        s[opening[-1]:i + 1] = reversed(s[opening[-1]:i + 1])
        opening.pop()
print(''.join(filter(lambda c: c != '\\' and c != '/', s)))