現在有一個字符串,你要對這個字符串進行 n 次操作,每次操作給出兩個數字:(p, l) 表示當前字符串中從下標爲 p 的字符開始的長度爲 l 的一個子串。你要將這個子串左右翻轉後插在這個子串原來位置的正後方,求最後得到的字符串是什麼。字符串的下標是從 0 開始的,你可以從樣例中得到更多信息。
輸入描述:
每組測試用例僅包含一組數據,每組數據第一行爲原字符串,長度不超過 10 ,僅包含大小寫字符與數字。接下來會有一個數字 n 表示有 n 個操作,再接下來有 n 行,每行兩個整數,表示每次操作的(p , l)。
保證輸入的操作一定合法,最後得到的字符串長度不超過 1000。
輸出描述:
輸出一個字符串代表最後得到的字符串。
輸入例子:
ab
2
0 2
1 3
輸出例子:
abbaabb
思路分析:1、獲取字符串的字串後進行反置(例如:abc變成cba);2、將反置後的子串添加在原字符串的後面。
C代碼如下:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void fanzhi(char *str);
void modify(char *str,int p,int l);
int main(void)
{
int i,n,p[100],l[100];
char *str = (char *)malloc(1000 * sizeof(char));
scanf("%s",str);
scanf("%d",&n);
for(i = 0;i < n;i++)
{
scanf("%d %d",&p[i],&l[i]);
}
for(i = 0;i < n;i++)
{
modify(str,p[i],l[i]);
}
printf("%s\n",str);
return 0;
}
void fanzhi(char *str)
{
int length,i;
char *temp;
length = strlen(str);
temp = (char *)malloc(length * sizeof(char));
for(i = 0;i < length;i++)
{
temp[i] = str[length - 1 - i];
}
temp[length] = '\0';
for(i = 0;i < length;i++)
{
str[i] = temp[i];
}
str[length] = '\0';
}
void modify(char *str,int p,int l)
{
int i,length;
char *temp = (char *)malloc(10 * sizeof(char));
length = strlen(str);
for(i = p;i < p + l;i++)
{
temp[i - p] = str[i];
}
temp[l] = '\0';
fanzhi(temp);
for(i = length;i < length + l;i++)
{
str[i] = temp[i - length];
}
str[length + l] = '\0';
}
此題博主覺得有些麻煩,求各位大神看看。