题目:
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) {
string res = "";
s += ' ';
int len = s.length(), e = len - 1, st = len - 1;
while (st >= 0) {
while (st >= 0 && s[st] == ' ')st--;
e = st + 1;
while (st >= 0 && s[st] != ' ')st--;
string sub="";
if (st != -1)sub = s.substr(st + 1, e - st);
else if (s[0] != ' ') sub = s.substr(0, e);
else sub = s.substr(1, e);
res += sub;
}
if (*(res.end() - 1) == ' ')res.erase(res.end() - 1);
s.swap(res);
}
};