Reverse string (2)
Title description
Given a character type array chas and an integer size, please move the left half of size to the right and the right half to the left.
Enter a description:
Enter two lines, the first line is an integer representing size, and the second line is a character string representing chas (1 ≤ size ≤ lengthchas ≤ 1 0 5) chas(1 \leq size\leq length_{chas} \leq 10^5 )c h a s ( 1≤size≤lengthc h a s≤105)
Output description:
Output a line of string, which represents the reversed string.
Example 1
enter
3
abcdefg
Output
defgabc
Remarks:
Time complexity O (n) O(n)O ( n ) , additional space complexityO (1) O(1)O ( 1 )。
answer:
First flip the left and right parts separately, and then flip the whole.
Code:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
char s[N];
void change(int l, int r) {
for (int i = l, j = r; i < j; ++i, --j)
swap(s[i], s[j]);
}
int main(void) {
int sze;
scanf("%d", &sze);
scanf("%s", s);
int len = strlen(s);
change(0, sze - 1);
change(sze, len - 1);
change(0, len - 1);
puts(s);
return 0;
}