[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;
}