Question: Put the sentence "I love you baby" into an inverted "baby you love I ".
Original post and solution: http://blog.csdn.net/lizhongkan/archive/2009/10/21/4708300.aspx
The solution of the original post is to use the auxiliary space. Here I will talk about my own solution,AlgorithmIn-situ operation, no auxiliary strings are needed.
The solution consists of three steps:
(1) Determine whether the character is a letter. Refer to the library function implementation:
Inline bool isalpha (char C)
{
Return (unsigned INT) (c | 0x20)-'A') <26u;
}
(2) Reverse the string of the specified length
Inline void inverse (char * STR, int nlen)
{
Char ctemp;
If (nlen <= 1)
Return;
For (INT I = 0; I <nlen/2; I ++)
{
Ctemp = STR [I];
STR [I] = STR [nLen-1-i];
STR [nLen-1-i] = ctemp;
}
}
(3) Algorithm Implementation: first, the entire string is reversed to ybab ym evol I, and then each word is reversed to: Baby my love I
Void inversestr (char * Str)
{
Char * P = STR;
Int nlen = strlen (STR );
Int nsublen = 0;
// Overall reverse Configuration
Inverse (STR, nlen );
// Reverse word placement
For (INT I = 0; I <= nlen; I ++)
{
If (isalpha (STR [I])
{
Nsublen ++;
}
Else
{
Inverse (p, nsublen );
P = STR + I + 1;
Nsublen = 0;
}
}
}
I personally feel that this writing method is clearer, and the first two tool functions are designed as inline functions, so there is no function call overhead problem. Of course, the solution of the original post is also good. We look forward to providing more efficient algorithms ~