试题 算法提高 字符串的操作


资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
  给出一个字符串S,然后给出q条指令,分别有4种:

  1. Append str
  表示在S的最后追加一个字符串str。
  例:
  原字符串:ABCDE
  执行 Append FGHIJ 后
  字符串变为:ABCDEFGHIJ

  2. Insert x str
  表示在位置x处插入一个字符串str。(输入保证0<x<=当前字符串长度)
  例:
  原字符串:ABCGHIJ
  执行 Insert 4 DEF 后
  字符串变为:ABCDEFGHIJ

  3. Swap a b c d
  表示交换从第a位到第b位的字符串与从第c位到第d位的字符串。(输入保证0<a<b<c<d<=当前字符串长度)
  例:
  原字符串:ABGHIFCDEJ
  执行 Swap 3 5 7 9后
  字符串变为:ABCDEFGHIJ

  4. Reverse a b
  表示将从第a位到第b位的字符串反转。(输入保证0<a<b<=当前字符串长度)
  例:
  原字符串:ABGFEDCHIJ
  执行 Reverse 3 7 后
  字符串变为:ABCDEFGHIJ

  最后输出按顺序执行完指令后的字符串。
输入格式
  输入第一行包含字符串S,第二行包含一个整数q,接下来q行分别为q个指令。
输出格式
  输出为1行,为按顺序执行完输入指令后的字符串。
样例输入
My
5
Append Hello
Insert 3 dlroW
Reverse 3 7
Swap 3 7 8 12
Swap 1 2 3 7
样例输出
HelloMyWorld
样例说明
  原字符串:My
  执行 Append Hello 后:MyHello
  执行 Insert 3 dlroW 后:MydlroWHello
  执行 Reverse 3 7 后:MyWorldHello
  执行 Swap 3 7 8 12 后:MyHelloWorld
  执行 Swap 1 2 3 7 后:HelloMyWorld
数据规模和约定
  对于30%的数据,q=1;

  对于70%的数据,如有Swap指令,Swap指令中b-a=d-c;

  对于100%的数据,最终字符串长度不大于40000,1<=q<=150
  
PS:注意要对字符串本身进行操作,而不是截取字符串出来操作,这样是不会改变输出结果的。

#include<bits/stdc++.h>
using namespace std;

int main(){
string S;
int Qn;
cin>>S>>Qn;
string command[Qn];
for(int i=0;i<Qn;i++){
cin>>command[i];
if(command[i]=="Append"){
string str1;
cin>>str1;
S.append(str1);
}
else if(command[i]=="Insert"){
int index;
string str2;
cin>>index>>str2;
S.insert(index-1,str2);
}
else if(command[i]=="Swap"){
int a,b,c,d;
cin>>a>>b>>c>>d;
string s1,s2,s3,s4,s5;
s1=S.substr(0,a-1);
s2=S.substr(a-1,b-a+1);
s3=S.substr(b,c-b-1);
s4=S.substr(c-1,d-c+1);
s5=S.substr(d,S.length()-d);
S=s1+s4+s3+s2+s5;
}
else if(command[i]=="Reverse"){
int e,f;
cin>>e>>f;
string s1,s2,s3;
s1=S.substr(0,e-1);
s2=S.substr(e-1,f-e+1);
s3=S.substr(f,S.length()-f);
reverse(s2.begin(),s2.end());
S=s1+s2+s3;
}
}
cout<<S;
return 0;
}