面试题42:左旋转字符串
/*题目:定义一个函数实现字符串左旋转操作的功能。字符串的左旋转操作就是把字符串前面的若干个字符转移到字符串的
尾部。比如输入字符串"abcdefg"和2,该函数将返回左旋转2位得到的结果"cdefgab"。*/
#include <iostream>
#include <cstring>
using namespace std;
//翻转字符串
void Reverse(char *pStart, char *pEnd)
{
if(pStart == NULL || pEnd == NULL)
return;
while(pStart < pEnd)
{
char tmp = *pStart;
*pStart = *pEnd;
*pEnd = tmp;
pStart++;
pEnd--;
}
}
//翻转英文句子
char *ReverseSentence(char *pData)
{
//定义并初始化翻转变量
char *pStart = pData;
char *pEnd = pData;
//将pEnd指向句子末尾的停止符
while(*pEnd != )
++pEnd;
//pEnd指向最后一个字符
--pEnd;
//此时pStart
//翻转整个句子
Reverse(pStart, pEnd);
//翻转后pStart仍指向第一个字符,pEnd仍指向最后一个字符(如果想改变pEnd和pStart,则要用到指向指针的指针)
//翻转句子中的每个单词(重新初始化)
pStart = pEnd = pData;
while(*pStart != )
{
if(*pStart == )
{
++pStart;
++pEnd;
}else if(*pEnd == || *pEnd == )
{
Reverse(pStart, --pEnd);
pStart = ++pEnd;//必须是++pEnd不能使pEnd++,pStart和pEnd均指向下
//一个单词的第一个字符
}else
{
++pEnd;
}
}
return pData;
}
//左旋字符串
char *LeftRotateString(char *pStr, int n)
{
if(pStr != NULL)
{
//强制类型转换(显式转换)为int型
int Length = static_cast<int> (strlen(pStr));
if(Length > 0 && n > 0 && n < Length)
{
char *pFirstStart = pStr;
char *pFirstEnd = pStr + n - 1;
char *pSecondStart = pStr + n;
char *pSecondEnd = pStr + Length - 1;
//翻转字符串的前面的n个字符
Reverse(pFirstStart, pFirstEnd);
//翻转字符串的后面的字符
Reverse(pSecondStart, pSecondEnd);
//翻转整个字符串
Reverse(pFirstStart, pSecondEnd);
}
}
return pStr;
}
//=========================测试代码=====================
void Test(char *TestName, char *Input, int n, char *ExpectedResult)
{
if(TestName != NULL)
cout << TestName << " begins:" << endl;
char *Result = LeftRotateString(Input, n);
if((Input == NULL && ExpectedResult == NULL) || (Input != NULL && strcmp(Result, ExpectedResult) == 0))
cout << "Passed!" << endl;
else
cout << "Failed!" << endl;
}
//========================测试用例=======================
//功能测试
void Test1()
{
char Input[] = "abcdefg";
char ExpectedResult[] = "cdefgab";
Test("Test1", Input, 2, ExpectedResult);
}
//左旋转一个字符
void Test2()
{
char Input[] = "abcdefg";
char ExpectedResult[] = "bcdefga";
Test("Test2", Input, 1, ExpectedResult);
}
//左旋转n - 1个字符(字符串长度为n)
void Test3()
{
char Input[] = "abcdefg";
char ExpectedResult[] = "gabcdef";
Test("Test3", Input, 6, ExpectedResult);
}
//左旋转0个字符
void Test4()
{
char Input[] = "abcdefg";
char ExpectedResult[] = "abcdefg";
Test("Test4", Input, 0, ExpectedResult);
}
//特殊输入,输入空字符串
void Test5()
{
Test("Test5", NULL, 6, NULL);
}
//左旋转n个字符(字符串长度为n)
void Test6()
{
char Input[] = "abcdefg";
char ExpectedResult[] = "abcdefg";
Test("Test6", Input, 7, ExpectedResult);
}
//左旋转n + 1个字符(字符串长度为n)
void Test7()
{
char Input[] = "abcdefg";
char ExpectedResult[] = "abcdefg";
Test("Test7", Input, 8, ExpectedResult);
}
int main()
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
return 0;
}
上一篇:
IDEA上Java项目控制台中文乱码
