Skip to content

Instantly share code, notes, and snippets.

@safeng
Created March 16, 2014 06:39
Show Gist options
  • Save safeng/9579402 to your computer and use it in GitHub Desktop.
Save safeng/9579402 to your computer and use it in GitHub Desktop.
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".
class Solution {
public:
void reverseWords(string &s) {
if(s.size() == 0)
return;
reverse(s.begin(), s.end());
// reverse word by word
istringstream iss(s);
string word;
ostringstream oss;
while(iss >> word)
{
reverse(word.begin(), word.end());
oss << word << ' ';
}
string res = oss.str();
if(res == "")
{
s=res;
}
else
{
s.assign(res.begin(), res.end()-1);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment