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 rs;
for (int i = s.length()-1; i >= 0; )
{
while (i >= 0 && s[i] == ' ') i--;
if (i < 0) break;
if (!rs.empty()) rs.push_back(' ');
int sublen = 0;
while (i >= 0 && s[i] != ' ')
{
sublen++;
i--;
}
string t = s.substr(i+1,sublen);
rs.append(t);
}
s = rs;
}
};

496

被折叠的 条评论
为什么被折叠?



