# 557. Reverse word III c in string++

Given a string, you need to reverse the character order of each word in the string while still preserving the initial order of spaces and words.

Example 1:

```Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
```

Note: in a string, each word is separated by a single space, and there are no extra spaces in the string.

I'm tired of this problem. I started to exceed the memory space limit

Failed solution and code: just stack each word, and then stack it once

```class Solution {
public:
string reverseWords(string s) {
stack<char> tmp;
string result;
int i = 0;
for(string::iterator iter = s.begin(); iter != s.end();iter++)
{
if(*iter != ' ')
{
tmp.push(*iter);
}
if(*iter == ' '||  *(iter + 1) == NULL)
{
while(!tmp.empty())
{
result = result + tmp.top();
tmp.pop();
}
if(*(iter + 1))
result = result + ' ';
}
}
return result;
}
};```

The final solution is as follows:

```class Solution {
public:
string reverseWords(string s) {
vector<int> a;
if(s.empty())
return s;
int i = 0;
for(auto c:s)
{
if(c == ' ')
a.push_back(i);
i++;
}
int size = a.size();
if(size == 0)
{
reverse(s.begin(),s.end());
return s;
}
reverse(s.begin(),s.begin()+a[0]);
for(int j = 0;j < size - 1;j++)
{
//cout << *(s.begin() + a[j]);
reverse(s.begin() + a[j] + 1, s.begin() + a[j + 1]);
}
reverse(s.begin()+a[size-1]+1,s.end());
return s;
}
};```

Posted by ozzythaman on Sun, 01 Dec 2019 01:28:28 -0800