标签:
要求时间对长度为n的字符串操作的复杂度为O(n),辅助内存为O(1)
char* LeftRotateString(char* pStr, int n)
{
if (pStr != NULL)
{
int nLength = static_cast<int>(strlen(pStr));
if (nLength > 0 && n > 0 && n < nLength)
{
char* pFirstStart = pStr;
char* pFirstEnd = pStr + n - 1;
char* pSecondStart= pStr + n;
char* pSecondEnd = pStr + nLength - 1;
//翻转字符串的前面n个字符
Reverse(pFirstStart, pFirstEnd);
//翻转字符串的后面部分
Reverse(pSecondStart, pSecondEnd);
//翻转整个字符串
Reverse(pFirstStart, pSecondEnd);
}
}
return pStr;
}
void Reverse(char* pBegin, char* pEnd)
{
if (pBegin == NULL || pEnd == NULL)
return;
while (pBegin < pEnd)
{
char temp = *pBegin;
*pBegin = *pEnd;
*pEnd = temp;
pBegin++, pEnd--;
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/wangfengfan1/article/details/46853855