算法竞赛入门经典(第二版)-刘汝佳-第六章 数据结构基础 例题 [Cloned] D - 破损的键盘 (p143, 链表)

题目链接:
https://vjudge.net/contest/276133#problem/D
题目:
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 <stdio.h>
#include <string.h>
//using namespace std;
char aa[1000005];
int last;
int cut;
int next[1000005];
int main()
{
	while(scanf("%s", aa + 1) == 1)   //让字母从1开始储存
	{
		int len = strlen(aa + 1);
		next[0] = 0;   //定义空节点
		last = cut = 0;
		for(int i = 1; i <= len; i++) //因为多一位所以要=len
		{
			char ch = aa[i];
			if(ch == '[')
			{
				cut = 0;   // 移动标点到开头
			}
			else if(ch == ']')
			{
				cut = last;// 移动标点到结尾
			}
			else 
			{
				next[i] = next[cut];
				next[cut] = i;
				if(cut == last) last = i;// 如果标点的值与最后节点的值相同,就移动最后节点的值
				cut = i;//移动标点
			}
		}
		for(int i = next[0]; i != 0; i = next[i])
		{
			printf("%c", aa[i]);
		}
		printf("\n");
		memset(aa, 0, sizeof(aa));// 清空数组
		memset(next, 0, sizeof(next));
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值