String: Reverse Words

Problem: Reverse the words in a sentence. For example "Hello World" should become "World Hello". Comment: This is one of most frequently asked interview questions on string manipulation.

Solution: First we reverse the entire string and then reverse each word of this reversed string.
"Hello World"
      |
   reverse
      |
      v
"dlroW olleH"
  |      |
reverse reverse
  |      |
  v      v
"World Hello"
Code:
void reverse(char str[], int beginIndex, int endIndex)
{
  while(beginIndex < endIndex) // keep swaping characters as long as
                               // begin index is less than end index
  {
     // swap the characters
     char temp = str[beginIndex]; 
     str[beginIndex] = str[endIndex];
     str[endIndex] = temp;

     beginIndex++; //increment the begin index
     endIndex--; //decrememnt the end index
  }
}

void reverse_words(char str[])
{
  reverse(str, 0, strlen(str)-1);
  int currentIndex = 0;
  int wordBeginIndex = 0;
  int wordEndIndex = -1;

  while(str[currentIndex])
  {
     if(str[currentIndex + 1] == ' '  // if we are at the word
        || str[currentIndex + 1] == '\0') // boundary or end of the string
     {
        wordEndIndex = currentIndex;
        reverse(str, wordBeginIndex, wordEndIndex);
        wordBeginIndex = currentIndex + 2;
     }
     currentIndex++;
  }
}

No comments:

Post a Comment