Created
March 16, 2014 06:39
-
-
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".
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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