题意
小可要使用文本编辑器写文章,编辑器支持如下四种操作:
1.Insert X : 在当前光标位置插入字符串x
2.Del : 删除光标前的一个字符串
3.Left : 光标向左移动一下
4.Right : 光标向右移动一下
给定一个n,和n次操作,问执行完这些操作后,光标前和光标后的内容是什么
解题思路
由于题目要求我们求出光标前后的内容,那么可以考虑使用两个栈分别存储光标前后的内容进行模拟,对于插入操作,可以将1号栈插入题目给出的单词,对于删除操作,可以在1号栈非空时删除栈顶元素,对于Left操作,可以在1号栈非空时将1号栈的栈顶插入到2号栈中,对于right操作,可以在2号栈非空时将2号栈的栈顶插入到1号栈中,最后输出两栈中的元素即可
AC代码
#include<bits/stdc++.h>
using namespace std;
int n;
string s,t,ans[100005];
stack<string> s1,s2;
int main(){
cin>>n;
while(n--){
cin>>s;
if(s=="Insert"){
cin>>t;
s1.push(t);
}
else if(s=="Left"){
if(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
}
else if(s=="Right"){
if(!s2.empty()){
s1.push(s2.top());
s2.pop();
}
}
else{
if(!s1.empty()){
s1.pop();
}
}
}
int cnt=0;
while(!s1.empty()){
cnt++;
ans[cnt]=s1.top();
s1.pop();
}
for(int i=cnt;i>=1;--i){
cout<<ans[i]<<" ";
}
cout<<"\n";
cnt=0;
while(!s2.empty()){
cnt++;
ans[cnt]=s2.top();
s2.pop();
}
for(int i=1;i<=cnt;++i){
cout<<ans[i]<<" ";
}
return 0;
}