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 reverse(string &s, int i, int j) { while(i<j) { char tmp = s[j]; s[j--] = s[i]; s[i++] = tmp; } } void reverseWords(string &s) { int i = 0, k = 0, j = 0; while(s[i] == ‘ ‘) i++; for(; i < s.size(); i++) { if(!(s[i] == ‘ ‘&&s[i] == s[i-1])) s[k++] = s[i]; } while(s[k-1] == ‘ ‘) k--; s.resize(k); reverse(s,0,k-1); i = 0; while(j < k) { while(s[j]!=‘ ‘&& j < k) j++; reverse(s,i,j-1); i = ++j; } } };
【LeetCode】Reverse Words in a String,布布扣,bubuko.com
【LeetCode】Reverse Words in a String
原文:http://blog.csdn.net/pyang1989/article/details/23625895