有一个字符串“student am i”,将它转换为“i am student”.(空间复杂度为O(1))
实现代码:
void swap(char *left, char *right )
{
char *ret = left ;
while (left < right)
{
int temp = *left ;
* left = *right ;
* right = temp;
left++;
right--;
}
}
char* Reverse(const char * str)
{
int len = strlen(str );
char *temp = str ;
char *start = str ;
char *end = str + len - 1;
swap(start, end);
while (*str )
{
start = str;
while (*str != ' '&&* str)
{
str++;
}
end = str - 1;
swap(start, end);
if (*str == ' ')
{
str++;
}
}
return temp;
}
int main()
{
char str[] = "student am i" ;
char *ret = Reverse(str);
printf( "%s\n", ret);
system( "pause");
return 0;
}