[My C language interview series] 013 word-based flip string

Source: Internet
Author: User
[My C language interview series] 013 word-based flip string

Flipped string in words

Original question: Write a function string reverse string word by word (string input) that reverses a string word by word.

For instance:

"The house is blue" --> "Blue is house"

"Zed is dead" --> "Dead is zed"

"All-in-One" --> "All-in-One"

Without adding any auxiliary array space, we can solve this problem:

Method 1:

1, Flip the entire string.

2, Flip every word.

Method 2:

1, Flip every word.

2, Flip the entire string.

Method 1 and method 2 are actually sequential issues, without affecting the time or space complexity of the algorithm.

 

The following code is provided: [this program is compiled in Dev C ++ 4.9.9.2]

# Include <stdio. h>

 

# Define is_print (CH)> 0x20 & (CH) <0x7e) // parse t Space

 

Char * reverseeveryword (char * Str );

Char * reversewholestring (char * Str );

Char * lr_reverse (char * left, char * right );

 

Int main (void)

{

Char STR [] = "Hello word! **";

Char * P = STR;

# If 0

Reversewholestring (STR );

Reverseeveryword (STR );

Puts (STR );

# Else

Reverseeveryword (STR );

Reversewholestring (STR );

Puts (STR );

# Endif

System ("pause ");

Return 0;

}

Char * reverseeveryword (char * Str)

{

Char * Right = STR, * Left = STR;

If (STR = NULL)

Return NULL;

While (! Is_print (* right ))

Right ++;

While (* right)

{

Left = right;

While (is_print (* right ))

Right ++;

Lr_reverse (left, right-1 );

While (* Right &&! Is_print (* right ))

Right ++;

}

Return STR;

}

Char * reversewholestring (char * Str)

{

Char * P = STR;

If (STR = NULL)

Return NULL;

While (* P) P ++;

P --;

Lr_reverse (STR, P );

Return STR;

}

Char * lr_reverse (char * left, char * right)

{

Char TT, * ret = left;

If (Left = NULL | right = NULL)

Return NULL;

While (left <right)

{

Tt = * left;

* Left ++ = * right;

* Right -- = tt;

}

Return ret;

}

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.