Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
1 class Solution { 2 public: 3 void reverseWords(string &s) 4 { 5 //从前往后扫描 6 string res, word; 7 for(int i = s.size()-1; i >= 0;) 8 { 9 while(i >= 0 && s[i] == ' ')--i;//去掉空格 10 if(i < 0)break; 11 if(res.size() != 0)res.push_back(' '); 12 word.clear(); 13 while(i >= 0 && s[i] != ' ')word.push_back(s[i--]);//word为找到的一个单词 14 for(int j = word.size()-1; j >= 0; --j) 15 res.push_back(word[j]); 16 } 17 s = res; 18 } 19 };
【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3986615.html