Uva 11988 (Broken Keyboard)悲剧文本

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

 1 /*Uva11988
 2 运用链表一个next[i]存储着下一个s[i]的位置,next[0]为表头,指向一开始需要输出的s[i]的值。
 3 */
 4 #include<iostream>
 5 #include<cstdio>
 6 #include<cstring>
 7 const int maxn = 100000 + 5;
 8 char s[maxn];
 9 int next[maxn];
10 int main()
11 {
12     while (scanf_s("%s", s + 1,maxn) == 1)
13     {
14         int n = strlen(s + 1);
15         next[0] = 0;
16         int cur = 0, last = 0;
17         for (int i = 1; i <= n; i++)
18         {
19             char ch = s[i];
20             if (ch == '[')cur = 0;//更新next[0]的指向
21             else if (ch == ']')cur = last;//使next[cur]指向【前的位置;即开始的链表被移动到了后方,
22                                           //【】内的内容被放在了前面
23             else
24             {
25                 /*此处类似于链表的添加,不断更新尾部地址*/
26                 next[i] = next[cur];//next[cur]存储的是下一个指向的地址
27                                     //若是普通情况,就将待打印字符(当前的最后一个字符)指向0
28                                     //如果遇到【】情况,当遇到了【,
29                                     //那么next[i]存储next[0]的值也就是next[i]指向了普通情况的第一个字符,
30                                     //同时更新next[0]的值指向【的下一个位置。
31                 next[cur] = i;//前一个位置的next存储着下一个next的地址即s[i]中的i
32                 if (cur == last)last = i;
33                 cur = i;
34             }
35         }
36         for (int i = next[0]; i != 0; i = next[i])
37             printf("%c", s[i]);
38         printf("\n");
39     }
40     return 0;
41 }

猜你喜欢

转载自www.cnblogs.com/Dinosaur-Po/p/12680634.html
今日推荐