字符串
字符串旋转
解法一:蛮力移位
//蛮力移位
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 LeftRotateStringManli(char* s,int n,int m)
{
while(m--)
{
LeftShiftOne(s,n);
}
}
测试结果:
cout << "开始" << endl;
Print(s,6);
cout <<" "<< endl;
LeftRotateString(s,6,3);
Print(s,6);
cout << "结束" << endl;
//运行时间26秒
解法二:三步反转
//三步反转法
void Revesestring(char*s ,int from,int to)
{
while(from<to)
{
char t=s[from];
s[from++]=s[to];
s[to--]=t;
}
}
void LeftRotateStringSanbu(char* s,int n,int m)
{
m%=n;
Revesestring(s,0,m-1);
Revesestring(s,m,n-1);
Revesestring(s,0,n-1);
}
测试结果:
char s[6]={'a','b','c','d','e','f'};
cout << "开始" << endl;
Print(s,6);
cout <<" "<< endl;
LeftRotateStringSanbu(s,6,3);
Print(s,6);
cout << "结束" << endl;
// 运行时间4秒
字符串包含