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"键(将光标移动到行尾)。每次输出最终显示的字符串。
题解:
每次输入的字符串可能会到奇怪的位置,此时直接存字符的位置会TLE。涉及到插入操作,所以用链表来实现,这里用
n
x
t
nxt
nxt数组来实现。
n
x
t
[
0
]
nxt[0]
nxt[0]表示起始位置的字符的下标(即链表头),其余位置
n
x
t
[
i
]
nxt[i]
nxt[i]表示
s
[
i
]
s[i]
s[i]对应的下一个字符所在的位置。这里用0来表示链表尾,所以读入字符串时从s[1]开始。例如第一个样例,
n
x
t
[
0
]
=
11
,
n
x
t
[
11
]
=
12
,
n
x
t
[
12
]
=
13...
n
x
t
[
15
]
=
1
,
n
x
t
[
1
]
=
2...
nxt[0]=11,nxt[11]=12,nxt[12]=13...nxt[15]=1,nxt[1]=2...
nxt[0]=11,nxt[11]=12,nxt[12]=13...nxt[15]=1,nxt[1]=2...
遇到’[‘或’]'时,执行相应操作,移动光标。用
c
u
r
cur
cur来表示当前光标的位置,
i
i
i表示字符串的下标。当输入字符时,将
n
x
t
[
c
u
r
]
nxt[cur]
nxt[cur]值赋给
n
x
t
[
i
]
nxt[i]
nxt[i](比如你在
1
,
2
1,2
1,2之间插入了
3
3
3,这里表示
3
3
3后面是
2
2
2),再将i赋值给
n
x
t
[
c
u
r
]
nxt[cur]
nxt[cur](表示
1
1
1后面是
3
3
3)。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 7;
int nxt[maxn], cur, last;
char s[maxn];
void solve() {
nxt[0] = 0;
cur = 0;//表示当前光标位置
last = 0;//表示最后链表中最后一个字符的下标
int len = strlen(s + 1);//strlen()放到for里面会TLE
for (int i = 1; i <= len; ++i) {
if (s[i] == '[') cur = 0;
else if (s[i] == ']') cur = last;//移动光标
else {
nxt[i] = nxt[cur];
nxt[cur] = i;//插入操作
if (cur == last) last = i;//如果是在链表尾插入,更新最后一个字符的下标
cur = i;//为连续插入字符做准备
}
}
for (int i = nxt[0]; i != 0; i = nxt[i]) printf("%c", s[i]);
puts("");
}
int main() {
while (~scanf("%s", s + 1))
solve();
return 0;
}