题目:定义字符串的左旋转操作:把字符串前面的若干个字符移动到字符串的尾部。如把字符串abcdef左旋转2位得到字符串cdefab。
请实现字符串左旋转的函数。要求时间对长度为n的字符串操作的复杂度为O(n),辅助内存为O(1)。
思想:旋转三次
#include <iostream>
#include <assert.h>
using namespace std;
void ReserveString(char *input, int begin, int end)
{
assert(begin<=end);
while(begin < end)
{
char temp=*(input+begin);
*(input+begin)=*(input+end);
*(input+end)=temp;
begin++;
end--;
}
}
void LeftRotateString(char* pStr, int n)
{
int len=strlen(pStr);
ReserveString(pStr, 0, n-1);
ReserveString(pStr, n, len-1);
ReserveString(pStr, 0, len-1);
}
void main()
{
char p[]="abcdefghijk";//如果改成char *p="abcdefghijk";会出现内存错误,原因是:char *p的p在常量区,不能再对其赋值
cout<<"旋转前字符串:"<<p<<endl;
LeftRotateString(p, 4);
cout<<"旋转后字符串:"<<p<<endl;
}