题目描述:
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) {
int len = s.length();
if (len == 0) return;
string ans = "";
for (int i = len - 1; i >= 0;){
int pos=s.rfind(' ', i);
if (pos != string::npos){
if (pos == i){ //跳过连续的空格
i = pos - 1;
continue;
}
if (ans=="")
ans = ans + s.substr(pos+1, i - pos);
else
ans = ans + " " + s.substr(pos + 1, i - pos);
i = pos-1;
}
else{
if (ans=="")
ans = ans + s.substr(0, i + 1);
else
ans = ans +" "+ s.substr(0, i+1);
break;
}
}
s = ans;
}
};