比如ABCDEFG,移3位变DEFGABC,要求空间复杂度O(1),时间复杂度O(n)。
void
*pszStringRotate(
char
*pszString, intnCharsRotate)
翻手算法:
设置有个函数为倒序排列:void Rorder(char *pF,char *pE);
voidRorder(char*pF, char*pE)
{
chartemp;
while(pF <= pE)
{
temp = *pF;
*pF = *pE;
*pE = temp;
}
}
void*pszStringRotate(char*pszString, intnCharsRotate)
{
char*pR = pszString;
intn = 0;
while(pszString + n++ ! = ‘\n’); //得到字符串长度
if(n < nCharsRotate) returnpR; //入口参数检测
Rorder(pszString, pszString + nCharsRotate ); //C B A
pszString = pR;//归位
Rorder( pszString + nCharsRotate, pszString + n - 1); //GFED
pszString = pR;
Rorder(pszString, pszString + n - 1); //DEFGABC
return pR;
}
ABCDEFG
第一步:局部翻转
ABC DEFG == = 》 CBA GFED
第二步:整体翻转
CBA GFED == = 》 DEFGABC