小明打字
分数 5
全屏浏览题目
切换布局
作者 朱允刚
单位 吉林大学
小明正使用Microsoft Word打一篇文档,文档只包含a-z的小写字母和空格,在打字过程中可能会一次或多次按下Home键、End键、←方向键、→方向键、Insert键、Backspace键。请编写程序,给定小明在键盘上按键的序列,输出小明屏幕上最终显示的文本。
提示:Home键会将当前光标移至文本开始位置,End键当前光标移至文本尾,←键和→键会使当前光标左移或右移一个位置(如果光标在文档头则无法左移,光标在文档尾则无法右移),Insert键会在插入和替换文本间切换(默认是插入状态),Backspace键会删除当前光标前的一个字符。
输入格式:
输入为不超过50000个字符,表示小明的按键序列。包含a-z的小写字母、空格以及字符[、]、{、}、-、=。其中字符“[”表示Home键,“]”表示End键,“{”表示←键,“}”表示→键,“-”表示Insert键,“=”表示Backspace键。
输出格式:
输出为在小明屏幕上最终显示的文本。最后一个字母后没有回车或换行。
输入样例1:
jilin[i lofe{{-v-} ] universiti=y
输出样例1:
i love jilin university
输入样例2:
abcd[c-de
输出样例2:
cdecd
输入样例3:
[[]][][]happy=birthday
输出样例3:
happbirthday
输入样例4:
efg[bbb}}=}}}}=[{{{{a
输出样例4:
abbbe
代码长度限制
16 KB
时间限制
100 ms
内存限制
10 MB
c++代码:
#include <cstring>
#include <iostream>
using namespace std;
// 定义双向链表结点结构体
typedef struct LNode{
char ch; // 结点存储的字符
struct LNode* next; // 指向下一个结点的指针
struct LNode* prev; // 指向上一个结点的指针
}*List;
int main(){
List first, end, tmp;
char ch;
List L = new LNode();
first = L; // 链表的头结点
end = L; // 链表的尾结点
tmp = L; // 当前操作的结点
bool isInsert = true; // 标记是否为插入模式
cin.get(ch); // 输入一个字符,不包括换行符 '\n'
while (ch != '\n'){
if (ch == '[') tmp = first;
else if (ch == ']') tmp = end;
else if (ch == '{'){
if (tmp->prev) tmp = tmp->prev; // 移动到上一个结点
}
else if (ch == '}'){
if (tmp->next) tmp = tmp->next; // 移动到下一个结点
}
else if (ch == '-') isInsert = !isInsert; // 切换插入模式
else if (ch == '='){
if (tmp->prev){ // 如果当前结点有前驱结点
List t = tmp;
tmp->prev->next = tmp->next; // 前驱结点的 next 指针指向当前结点的下一个结点
if (tmp->next){
tmp->next->prev = tmp->prev; // 下一个结点的 prev 指针指向当前结点的前驱结点
tmp = tmp->prev; // 移动到前驱结点
}
else{
tmp = tmp->prev;
tmp->next = NULL;
}
delete t; // 删除当前结点
if (tmp->next == NULL) end = tmp; // 如果当前结点是尾结点,更新 end 指针
}
}
else {
List ins = new LNode();
ins->ch = ch;
ins->next = tmp->next;
ins->prev = tmp;
tmp->next = ins;
tmp = ins;
if (tmp->next == NULL) end = tmp; // 如果当前结点是尾部插入的新结点,更新 end 指针
if (!isInsert && tmp->next){ // 如果当前为删除模式且当前结点后面还有结点
List t = tmp->next;
if (t->next){
tmp->next = t->next; // 调整当前结点和下一结点之间的连接关系
t->next->prev = tmp;
delete t; // 删除下一结点
}
else{
delete t;
end = tmp;
tmp->next = NULL; // 将当前结点设为尾部
}
}
}
cin.get(ch); // 继续输入下一个字符
}
List a = first->next;
while (a){
cout << a->ch; // 输出链表内容
a = a->next;
}
return 0;
}