Tuesday, August 12, 2008

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

//Idea here is to reverese the entire sentence, then reverse each word in it.
char* ReverseWords(char *pszString)
{
if (NULL == pszString)
return NULL;

char* pTemp = pszString;

//Reverse string
char *pLeft = pTemp;
char *pRight = pTemp;

//Find out the end of sentence
while (*pRight)
{
++pRight;
}

--pRight;

//Reverse sentence
while (pLeft < pRight)
{
char ch = *pLeft;
*pLeft = *pRight;
*pRight = ch;

++pLeft;
--pRight;
}

//Reverse words
while (*pTemp)
{
while ( (*pTemp == ' ') && (*pTemp) )
++pTemp;

pLeft = pTemp;

while ( (*pTemp != ' ') && (*pTemp) )
++pTemp;

pRight = pTemp - 1;

while (pLeft < pRight)
{
char ch = *pLeft;
*pLeft = *pRight;
*pRight = ch;

++pLeft;
--pRight;
}
}

return pszString;
}

0 comments: