现在有一个字符串,你要对这个字符串进行 n 次操作,每次操作给出两个数字:(p, l) 表示当前字符串中从下标为 p 的字符开始的长度为 l 的一个子串。你要将这个子串左右翻转后插在这个子串原来位置的正后方,求最后得到的字符串是什么。字符串的下标是从 0 开始的,你可以从样例中得到更多信息。
输入描述:
每组测试用例仅包含一组数据,每组数据第一行为原字符串,长度不超过 10 ,仅包含大小写字符与数字。接下来会有一个数字 n 表示有 n 个操作,再接下来有 n 行,每行两个整数,表示每次操作的(p , l)。
保证输入的操作一定合法,最后得到的字符串长度不超过 1000。
输出描述:
输出一个字符串代表最后得到的字符串。
输入例子:
ab 2 0 2 1 3
输出例子:
abbaabb
解题思路
法1:所反转字符串区间为[p,p+l-1],将其逆序存入另一字符串,然后使用string的insert库函数把该字符串插入到p+l位置即可。
法2:将[p+l,length-1]范围内字符后移l个单位,再把[p,p+l-1]逆序插入到p+l位置。
库函数笔记:
string的成员函数insert有以下多种重载:
string &insert(int p0, const char *s); //在p0位置插入字符串s(插入指针类型)
string &insert(int p0, const char *s, int n); //在p0位置插入字符串s的前n个字符
string &insert(int p0,const string &s); //在p0位置插入字符串s(插入string类型)
string &insert(int p0,const string &s, int pos, int n);//在p0位置插入字符串s从pos开始的连续n个字符
string &insert(int p0, int n, char c); //在p0处插入n个字符c
AC代码如下:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cin>>str;
int n;
cin>>n;
int p,l;
while( n-- ){
cin>>p>>l;
string b;
for( int i=p+l-1;i>=p;--i ){
b.push_back( str[i] );
}
str.insert( p+l,b );
}
cout<<str;
return 0;
}