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;
}