旋转字符串:将首个字符插入数组最后,并将剩余字符向前移动
暴力破解函数
//旋转字符串
// 把字符串“abcdef”前面的2个字符'a'和'b'移动到字符串的尾部
// 使得原字符串变成字符串“cdefab”
#include<stdio.h>
#include<WinSock2.h>
#include<stdlib.h>
//暴力破解法函数
void LeftShiftOne(char* s, int n);
void LeftRotateString(char* s, int n, int m);
//三步反转法函数
void ReverseStringBreak(char* s, int from, int to);
void LeftRotateStringBreak(char* s, int n, int m);
char s[] ="abcdef";
void main()
{
//获取数组长度,-1是去掉标识符位置
int arrSum = (sizeof(s) / sizeof(s[0]))-1;
//LeftRotateString(s,arrSum,2);
//printf("%s\t", s);
LeftRotateStringBreak(s, arrSum, 2);
printf("%s\t", s);
}
//暴力破解法
void LeftShiftOne(char* s, int n)
{
//遍历数组,将数组第一个字符放到最后,其余字符向前移动
char t = s[0];
for (int i = 1; i < n; i++)
{
s[i - 1] = s[i];
}
s[n - 1] = t;
}
void LeftRotateString(char* s, int n, int m)
{
//将多次执行把数组第一个字符放到最后
while (m--)
LeftShiftOne(s, n);
}
三步反转法函数
//三步反转法
#include<stdio.h>
//字符调换
void ReverseStringBreak(char* s, int from, int to)
{
printf("%s %d %d\n", s,from, to);
while (from < to)
{
char t = s[from];
s[from] = s[to];
s[to] = t;
from++;
to--;
//等同于s[from++] s[to--]
printf("%s %d %d\n",s,from,to);
}
}
//执行3次字符调换 "s"代表数组,"n"代表数组长度,"m"代表要移动的位数
void LeftRotateStringBreak(char* s, int n, int m)
{
m%=n; //如果要左移动大于n位,那m和%n是等价的
printf("%d %d\n",m,n);
ReverseStringBreak(s, 0, m - 1);//作用:abc->cba
printf("\n");
ReverseStringBreak(s, m, n - 1);//作用:def->fed
printf("\n");
ReverseStringBreak(s, 0, n - 1);//作用:cbafed->defabc
printf("\n");
}