键盘有毒(STL() || 数组模拟双向链表)

ACM汇总学习:https://blog.csdn.net/weixin_39778570/article/details/83187443
Broken Keyboard
题目:https://vjudge.net/problem/UVA-11988
Sample Input
This_is_a_[Beiju]_text
[[]][][]Happy_Birthday_to_Tsinghua_University
Sample Output
BeijuThis_is_a__text
Happy_Birthday_to_Tsinghua_University
题意:输入一个字符串,每次把字符串中[]中的字符串移动到字符串的最前面,最后输出
解法:使用链表,每次执行插入操作就行,[]中的插在前面,其他的插在后面
STL版本,容易理解

#include<bits/stdc++.h>
#define ll long long
#define fo(i,j,n) for(register int i=j; i<=n; ++i)
using namespace std;
const int maxn = 1e5 + 5;
char s[maxn];
list<char> L;
int main(){
	while(scanf("%s",s+1)!=EOF){
		L.clear();
		auto it = L.begin();
		auto tail = L.end();
		int len = strlen(s+1);
		char ch;
		fo(i,1,len){
			ch = s[i];
			if(ch=='[') it = L.begin();
			else if(ch==']') it = L.end();
			else{
			//	putchar(*it);  // 头指针 
				it = L.insert(it,ch); // 注意要返回指针!!!
			//	putchar(*it);  // 当前指针 
				it++;          // 指针移动到下一位,移动到头指针 
			//	putchar(*it);  // 头指针 
			}
		}
		for(char c : L)putchar(c);
		putchar(10);
	}
	return 0;
} 

紫书,数组模拟,重点理解插入,每次插入到cur前面

#include<bits/stdc++.h>
#define ll long long
#define fo(i,j,n) for(register int i=j; i<=n; ++i)
using namespace std;
const int maxn = 1e5+5;
int nxt[maxn]; 
char s[maxn];
int main(){
	while(scanf("%s",s+1)!=EOF){
		int len = strlen(s+1);
		char ch;
		int cur=0,tail=0,head=0; // 一开始next[cur]=0表示光标之后啥也没有
		memset(nxt,0,sizeof(int)*(len+1)); 
		fo(i,1,len){
			ch = s[i];
			if(ch=='[') cur = 0; // 光标移动到头部 
			else if(ch==']') cur = tail; // 光标移动到尾部
			else{
				nxt[i] = nxt[cur]; //  i位置变为新的光标 (插在nxt[cur]前) (插) 
				nxt[cur] = i;       // 光标读入内容(跳动光标),这一行才是输出的关键 (读) 
				if(tail==cur) tail = i; // 同步移动 
				cur = i; // 更新当前光标,即下一个字符插在i之后 
			} 
		}
		for(int i=nxt[head]; i; i=nxt[i])putchar(s[i]);
		putchar(10); 
	}
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值