Efficiently reverse the order of the words (not characters) in an array of characters

前端 未结 21 1957
[愿得一人]
[愿得一人] 2020-11-28 04:40

Given an array of characters which forms a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.

Example input and

21条回答
  •  时光说笑
    2020-11-28 04:54

    The algorithm to solve this problem is based on two steps process, first step will reverse the individual words of string,then in second step, reverse whole string. Implementation of algorithm will take O(n) time and O(1) space complexity.

          #include 
          #include 
    
          void reverseStr(char* s, int start, int end);
    
          int main()
          {
                  char s[] = "This is test string";
    
                  int start = 0;
                  int end = 0;
                  int i = 0;
    
                  while (1) {
    
                  if (s[i] == ' ' || s[i] == '\0')
                  {
                        reverseStr(s, start, end-1);
                        start = i + 1;
                        end = start;
                  }
                  else{
                        end++;
                  }
    
                  if(s[i] == '\0'){
                       break;
                  }
                  i++;
          }
    
          reverseStr(s, 0, strlen(s)-1);
          printf("\n\noutput= %s\n\n", s);
    
          return 0;
      }
    
      void reverseStr(char* s, int start, int end)
      {
         char temp;
         int j = end;
         int i = start;
    
         for (i = start; i < j ; i++, j--) {
              temp = s[i];
              s[i] = s[j];
              s[j] = temp;
         }
     }
    

提交回复
热议问题