Liu rujia's question, tragic text-_-|
Here, we use the vector <string> container to record the data in an inverted manner, and then output the data from the back.
The difficulty is that you do not know where such documents start to output. Therefore, it is better to use containers that dynamically manage memory.
I/O processing added to the O (n) algorithm is not listed, depressing.
#include <stdio.h>#include <vector>#include <string>using std::vector;using std::string;const int MAX_B = 5120;int id = 0, len = 0;char buf[MAX_B];inline char getFromBuf(){if (id >= len){len = fread(buf, 1, MAX_B, stdin);id = 0;}return buf[id++];}int oid = 0;int FLASH_P = MAX_B - 2;char outBuf[MAX_B];inline void charToBuf(char c){if (oid > FLASH_P){fwrite(outBuf, 1, oid, stdout);oid = 0;}outBuf[oid++] = c;}inline void flashLeft(){if (oid) fwrite(outBuf, 1, oid, stdout);}int main(){char c;while (c = getFromBuf()){if (!len) break;vector<string> vstr(1);int cur = 0;int end = 0;while (len && c != '\n'){if (c == '['){vstr.push_back(string());end++;cur = end;}else if (c == ']'){if (vstr.size() > 1 && vstr[vstr.size()-1].empty())end--, vstr.pop_back();cur = 0;}else vstr[cur].push_back(c);c = getFromBuf();}for (int i = (int)vstr.size() - 1; i >= 0 ; i--){for (int j = 0; j < (int)vstr[i].size(); j++){charToBuf(vstr[i][j]);}}charToBuf('\n');}flashLeft();return 0;}