## Tuesday, November 25, 2014

### [LeetCode] Reverse Words in a String

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.

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30``` ```class Solution { public: void reverseWords(string &s) { if(s.empty()) return; string ret, word; for(int i=s.size()-1; i>=0; i--) { if(isspace(s[i])) { if(i

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16``` ```class Solution { public: void reverseWords(string &s) { string ret; int j = s.size(); for(int i=s.size()-1; i>=0; i--) { if(s[i]==' ') j = i; else if(i==0 || s[i-1]==' ') { if(!ret.empty()) ret.append(" "); ret.append(s.substr(i, j-i)); } } s = ret; } }; ```

1. C++ Program to Reverse a Strings

Reverse a String means reverse the position of all character of String. You can use swapping concept to reverse any string in c++.

1. You made a silly comment on a code expert's blog, bro.

2. This comment has been removed by the author.

3. I think what he means might be, there is in place solution, but only for c/c++.

2. Reverse string and reverse words in a string are completely different concepts.

3. This solution is clean and dense, thanks for sharing.