Reverse the words in the string (leetcode 4.10 punches daily)

Given a string, flip each word in the string one by one.
 
Example 1:
输入: "the sky is blue"
输出: "blue is sky the"

Example 2:
Input: "hello world!"
Output: "world! Hello"
Explanation: The input string can contain extra spaces before or after, but the reversed characters cannot be included.

Example 3:
Input: "a good example"
Output: "example good a"
Explanation: If there are extra spaces between the two words, reduce the space between the inverted words to only one.

 
Description:

 The characters without spaces form a word.
 The input string can contain extra spaces before or after, but the reversed characters cannot be included.
 If there are extra spaces between the two words, reduce the spaces between the words after inversion to only one.
 
Idea: First remove the head and tail and the enclosed spaces, then use the word array to record each word, and then enter them into s in reverse order.
Learning: Because online oj is not a test sample to execute the total program once, global variables should be cleared once.
 1 char dealS[10000] = { 0 };
 2 char word[10000] = { 0 };
 3 
 4 char* reverseWords(char* s)
 5 {
 6     int temBegin;
 7     int temEnd;
 8     int k = -1,l = -1;
 9     int len = strlen(s);
10     memset()
11     for (temBegin = 0; temBegin < strlen(s); temBegin++)  // Delete the leading space 
12      {
 13          if (s [temBegin]! = '  ' )
 14              break ;
 15      }
 16  
17      for (temEnd = strlen (s) -1 ; temEnd> = 0 ; temEnd--)   // Delete Ending space 
18      {
 19          if (s [temEnd]! = '  ' )
 20              break ;
 21      }
 22      for ( int i = temBegin; i <temEnd + 1 ; i ++) // Delete midway space 
23     {
 24          if (s [i]! = '  ' )
 25          {
 26              dealS [++ k] = s [i];
 27          }
 28          else  if (s [i] == '  ' )
 29          {
 30              if (s [ i + 1 ] == '  ' )   // Continuous spaces 
31                  continue ;
 32              else 
33                  dealS [++ k] = '  ' ;
 34          }
 35      }
 36     
37     k = -1;
38     memset(s, 0, len);  //清空s
39     for (int i = strlen(dealS)-1; i >= 0; i--)
40     {
41         while (dealS[i] != ' ' && i != -1)
42         {
43             word[++l] = dealS[i];
44             i--;
45         }
46         
47         for (int j = l; j >= 0; j-- )
 48          {
 49              s [++ k] = word [j];
 50          }
 51          if (i! = 0 )   // if not the last 
52          {
 53              s [++ k] = '  ' ;
 54          }
 55          memset (word, 0 , l + 1 ); // Empty word 
56          l = -1 ;
 57      }
 58      s [k] = ' \ 0 ' ;
 59      return s;
60 }

 

 

 
 

Guess you like

Origin www.cnblogs.com/ZhengLijie/p/12672521.html