题目:字符串中单词的逆转,即将单词出现的顺序进行逆转。如将“Today is Friday!"逆转为"Firday! is Today”。(2012 百度、人人)
思路:如果想要不实用额外的空间,可以分为两步,首先将字符串全部逆转,然后通过空格分隔单词,使单词自身再次逆转。
代码:
#include<cstdio>
#include<cstring>
using namespace std;
void Reverse(char * begin, char * end)
{
if(begin==NULL||end == NULL) return;
while(begin<end)
{
char temp = *begin;
*begin = *end;
*end = temp;
begin++;
end--;
}
}
void ReverseSentence(char * str)
{
if(str==NULL) return;
char * begin = str;
char * end = str + strlen(str) -1;
Reverse(begin,end);
begin = str;
end = str;
while(*begin!='\0')
{
if(*begin==' ')
{
begin++;
end++;
}
else if(*end==' '||*end=='\0')
{
end--;
Reverse(begin,end);
end++;
begin=end;
}
else
end++;
}
}
int main()
{
char str[1000]={0};
while(gets(str))
{
ReverseSentence(str);
printf("%s\n",str);
}
}