题目描述:牛客NC15975小C的记事本

传送门:牛客

题目描述:

小C最近学会了java小程序的开发,他很开心,于是想做一个简单的记事本程序练练手。
他希望他的记事本包含以下功能:
1、append(str),向记事本插入字符串 str(英文字符)
2、delete(k),删除记事本最后k个字符(保证不为空串)
3、print(k),输出记事本第k个字符(保证不为空串)
4、undo(),撤销最近的1(或者)操作,使记事本回到1(或者2)操作之前的状态
可怜的小C琢磨了半天还是做不来,聪明的你能解决小C的问题吗?
输入:
8
1 ab
3 2
2 2
1 cd
3 1
4
4
3 1
输出:
b
c
a

算是一道简单题

对于这种需要保存之前的状态的题目,我们一般都会采用来做

具体思路:

对于我们的字符串插入,我们直接使用字符串相加来添加(注意如果栈为空时,使用S.top()会发生奇怪的错误)

对于我们的字符串删除操作,我们使用substr函数来解决,不知可百度

对于输出,直接使用S.top来取得此时此刻状态的字符串即可

对撤销这个操作因为我们是用stack来储存每一次的状态的,因此直接pop即可,注意此时题目中似乎忘记了空串的情况,我实现过程中忘记了判断但是依旧过了(所以下面我的AC代码也是没有补上的,我比较懒,你们加上即可)

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <string.h>
#include <stack>
using namespace std;
typedef long long ll;
#define inf 0x3f3f3f3f
#define root 1,n,1
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
inline ll read() {
	ll x=0,w=1;char ch=getchar();
	for(;ch>'9'||ch<'0';ch=getchar()) if(ch=='-') w=-1;
	for(;ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0';
	return x*w;
}
#define maxn 1000000
#define ll_maxn 0x3f3f3f3f3f3f3f3f
const double eps=1e-8;
int q;
stack<string>s;
int main() {
	int n;
	while(cin>>n) {
		int opt;string shuru;
		while(s.size()) s.pop();
		while(n--) {
			opt=read();
			if(opt==1) {
				cin>>shuru;
				if(s.size()==0) {
					s.push(shuru);
				}else {
					s.push(s.top()+shuru);
				}
			}else if(opt==2) {
				int k;
				k=read();
				s.push(s.top().substr(0,s.top().length()-k));
			}else if(opt==3) {
				int k;
				k=read();
				cout<<s.top()[k-1]<<endl;
			}else if(opt==4) {
				s.pop();
			}
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值