some algorithmic puzzles, tutorials, interview questions... and stuff...

Friday, October 02, 2009

How to reverse the order of words in a sentence but also each word

This is a common trick which can be done using pointers in C/C++, but the principle is the same for other languages: first reverse the whole sentence, disregarding the words, then reverse each word by itself (words are separated by whitespace).

The method to reverse a string is easy:

   1:  void reverseWord(char*& word, int len) {
   2:      for (int i = 0; i < len / 2; i++) {
   3:          char temp = word[i];
   4:          char temp2 = word[len - i - 1];
   5:          *(word +i) = temp2;
   6:          word[len - i - 1] = temp;
   7:      }
   8:  }

So we could use the above function to reverse the order of words in a sentence and also the letters in each word:

   1:      string s = "This is a test run";
   2:      char* str = const_cast<char*>(s.c_str());
   3:      int size = s.size();
   4:      cout << "Initial string is: ";
   5:      for (int i = 0; i < size; i++)
   6:          cout << str[i];
   7:      cout << endl;
   8:      reverseWord(str, size);
   9:      cout << "Whole string reversed is: ";
  10:      for (int i = 0; i < size; i++)
  11:          cout << str[i];
  12:      cout << endl;
  13:      // do stuff here
  14:      int k = 0;
  15:      int start = 0;
  16:      char* tmp = str;
  17:      while (k <= size) {
  18:          if (str[k] == ' ' || str[k] == '\0') {
  19:              reverseWord(tmp, k - start);
  20:              tmp = str + k + 1;
  21:              start = k + 1;
  22:          }
  23:          ++k;
  24:      }
  25:      //
  26:      cout << "After processing, string is: ";
  27:      for (int i = 0; i < size; i++)
  28:          cout << str[i];
  29:      cout << endl;


The complexity is... O(n) ?

No comments:

Post a Comment