阿里巴巴的实习生笔试题,实现将字符串按特定分隔符进行反转,如“www.taobao.com”,反转后为"com.taobao.www",要求时间复杂度为O(n),空间复杂度为O(1).
解题思想:用两个指针记录分隔符之间的子字符串,然后先将子字符串进行反转,逐段全部反转后,再将整个字符串进行一次反转。
#include <stdio.h>
#include <iostream>
using namespace std;
/*reverse a word*/
void reverseWord(char *pStart, char *pEnd)
{
while(pStart < pEnd)
{
char temp = *pStart;
*pStart++ = *pEnd;
*pEnd-- = temp;
}
}
/*reverse a whole sentense*/
void reverseSentense(char *pStart, char *pEnd)
{
while(pStart < pEnd)
{
char temp = *pStart;
*pStart++ = *pEnd;
*pEnd-- = temp;
}
}
void reverse(char szCh[], char splitor)
{
if(szCh == NULL)
return;
char *pStart = szCh;
char *pEnd = szCh;
while(*pEnd)
{
if(*pEnd == splitor)
{
reverseWord(pStart, pEnd-1);
pEnd++;
pStart=pEnd;
}
else
{
pEnd++;
}
}
reverseWord(pStart, pEnd-1); //reverse the last word
reverseSentense(szCh, pEnd-1); //reverse the whole sentense
}
int main()
{
//test1
char szCh[] = "www.taobao.com";
char splitor = '.';
cout<<"original: "<<szCh<<endl;
reverse(szCh, splitor);
cout<<"output: "<<szCh<<endl;
//test2
char szCh2[] = "sports.sina.com.cn";
char splitor2 = '.';
cout<<"original: "<<szCh2<<endl;
reverse(szCh2, splitor2);
cout<<"output: "<<szCh2<<endl;
//test3
char szCh3[] = "fdafd.";
char splitor3 = '.';
cout<<"original: "<<szCh3<<endl;
reverse(szCh3, splitor3);
cout<<"output: "<<szCh3<<endl;
//test3
char szCh4[] = ".fdafd";
char splitor4 = '.';
cout<<"original: "<<szCh4<<endl;
reverse(szCh4, splitor4);
cout<<"output: "<<szCh4<<endl;
getchar();
return 0;
}