Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
- Reduce them to a single space in the reversed string.
class Solution {
private:
void reviseString(string &s)
{
char *pCur = &s.at(0);
char *pCopy = pCur;
while (*pCur != '\0')
{
while (*pCur != '\0' && *pCur == ' ' )
{
pCur++;
}
if (*pCur == '\0')
{
*pCopy = '\0';
break;
}
while (*pCur != '\0' && *pCur != ' ')
{
*pCopy++ = *pCur++;
}
if (*pCur == '\0')
{
*pCopy = '\0';
break;
}
*pCopy++ = ' ';
pCur++;
}
if ( (pCopy != &s.at(0)) && (*(pCopy-1) == ' '))
*(pCopy-1) = '\0';
return;
}
void reverseInternal(char *begin, char *end)
{
while (end > begin)
{
char temp = *end;
*end = *begin;
*begin = temp;
end--;
begin++;
}
}
public:
void reverseWords(string &s) {
if (s.size() == 0)
return;
reviseString(s);
if (s.size() == 0)
return;
char *pBegin = &s.at(0);
char *pEnd = pBegin+s.size()-1;
// reverse the whole string
reverseInternal(pBegin, pEnd);
pBegin = pEnd = &s.at(0);
// reverse each word
while (*pEnd != '\0')
{
while(*pEnd != ' ' && *pEnd != '\0')
{
pEnd++;
}
char *pTemEnd = pEnd-1;
reverseInternal(pBegin, pTemEnd);
if (*pEnd == '\0')
return;
pBegin = ++pEnd;
}
}
};