[Original] Reverse string

Source: Internet
Author: User

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 ~

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.