Broken Keyboard (a.k.a. Beiju Text)
You’re typing a long text with a broken keyboard. Well it’s not so badly broken. The only problem with the keyboard is that sometimes the “home” key or the “end” key gets automatically pressed (internally).
You’re not aware of this issue, since you’re focusing on the text and did not even turn on the monitor! After you finished typing, you can see a text on the screen (if you turn on the monitor).
In Chinese, we can call it Beiju. Your task is to find the Beiju text.
Input
There are several test cases. Each test case is a single line containing at least one and at most 100,000
letters, underscores and two special characters ‘[’ and ‘]’ . ‘[‘means the “Home” key is pressed internally, and ‘]’ means the “End” key is pressed internally. The input is terminated by end-of-file (EOF).
Output
For each case, print the Beiju text on the screen.
Sample Input
This_is_a_[Beiju]_text
[[]][][]Happy_Birthday_to_Tsinghua_University
Sample Output
BeijuThis_is_a__text
Happy_Birthday_to_Tsinghua_University
你有一个破损的键盘。键盘上的所有键都可以正常工作,但有时Home键或者End键会自动按下。你并不知道键盘存在这一问题,而是专心地打稿子,甚至连显示器都没打开。当你打开显示器之后,展现在你面前的是一段悲剧的文本。你的任务是在打开显示器之前计算出这段悲剧文本。
输入包含多组数据。每组数据占一行,包含不超过100000个字母、下划线、字符“[”或者“]”。其中字符“[”表示Home键,“]”表示End键。输入结束标志为文件结束符(EOF)。输入文件不超过5MB。对于每组数据,输出一行,即屏幕上的悲剧文本。
样例输入:
This_is_a_[Beiju]_text
[[]][][]Happy_Birthday_to_Tsinghua_University
样例输出:
BeijuThis_is_a__text
Happy_Birthday_to_Tsinghua_University
#include <cstdio>
#include <string>
#include <iostream>
using namespace std;
struct Node{
char c;
Node *next;
};
Node *head;
Node *tail;
Node *p;
int main() {
string words;
while(cin >> words) {
// 初始化头结点指针
head = new Node;
// 头结点next域置空
head->next = NULL;
// 初始化尾结点指针
tail = head;
// 初始化辅助插入结点指针
p = head;
for(int i = 0; i < words.length(); i++) {
// 获取一个单词
char c = words[i];
// home键
if(c == ‘[‘) {
// 重新从头部插入
p = head;
} else if (c == ‘]‘) {
// end键
// 重新从尾部插入
p = tail;
} else {
// 插入该单词
// 借鉴了尾插法
Node *n = new Node;
n->c = c;
// 插入结点的下一个节点为辅助结点下一个结点
n->next = p->next;
// 辅助结点下一个结点为插入结点
p->next = n;
// 辅助结点指针指向插入结点
p = n;
// 辅助结点下一个结点为插入结点下一个结点
// 也就是说辅助结点指向了插入结点,但是辅助结点的下一个结点还是未添加插入结点的那个结点
p->next = n->next;
// tail指针永远指向尾部
// 只有在输入end键之后,tail指针才会向后移动
if(p->next == NULL) {
tail = p;
}
}
}
// 遍历输出
p = head ->next;
while(p != NULL) {
cout << p->c;
p = p->next;
}
printf("\n");
}
return 0;
}