#include <stdio.h>
#include <string.h>
#define NMAX 1000
void RotateVector(char arr[], unsigned int index, unsigned int n);
int main()
{
char str[NMAX];
unsigned int i, n;
printf("Input a string for rotating left.\n");
fgets(str, NMAX, stdin);
n = strlen(str) - 1;
str[n] = '\0';
printf("%d chars in the string.\n", n);
printf("How many position (i) to rotate?\n");
scanf("%u", &i);
RotateVector(str, i, n);
printf("After rotated %d positions\n", i);
printf("%s\n", str);
return 0;
}
/*Rotate the vector string arr by index positions.*/
void RotateVector(char arr[], unsigned int index, unsigned int n)
{
unsigned int i, j;
char t;
index %= n;
if (index == 0) {
return;
}
/*Reverse 'arr' in range between 0 and index-1*/
for(i = 0, j = index-1; i < j; i++, j--) {
t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
/*Reverse 'arr' in range between index and n-1*/
for(i = index, j = n-1; i < j; i++, j--) {
t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
/*Reverse 'arr' in range between 0 and n-1*/
for(i = 0, j = n-1; i < j; i++, j--) {
t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
#include <string.h>
#define NMAX 1000
void RotateVector(char arr[], unsigned int index, unsigned int n);
int main()
{
char str[NMAX];
unsigned int i, n;
printf("Input a string for rotating left.\n");
fgets(str, NMAX, stdin);
n = strlen(str) - 1;
str[n] = '\0';
printf("%d chars in the string.\n", n);
printf("How many position (i) to rotate?\n");
scanf("%u", &i);
RotateVector(str, i, n);
printf("After rotated %d positions\n", i);
printf("%s\n", str);
return 0;
}
/*Rotate the vector string arr by index positions.*/
void RotateVector(char arr[], unsigned int index, unsigned int n)
{
unsigned int i, j;
char t;
index %= n;
if (index == 0) {
return;
}
/*Reverse 'arr' in range between 0 and index-1*/
for(i = 0, j = index-1; i < j; i++, j--) {
t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
/*Reverse 'arr' in range between index and n-1*/
for(i = index, j = n-1; i < j; i++, j--) {
t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
/*Reverse 'arr' in range between 0 and n-1*/
for(i = 0, j = n-1; i < j; i++, j--) {
t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
算法非常简单,也非常好实现,执行效率也很高,时间复杂度为O(n),空间复杂度仅为O(1) 。