Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
class Solution {
public:
void reverseWords(string &s)
{
string st;
int i = s.length()-1;
while (i >= 0)
{
while(i >= 0 && s[i] == ' ') i--;
if(i < 0) break;
string stmp;
while (i >= 0 && s[i] != ' ') // 判断是一定要 “i>=0”在前,如果“s[i] != 0”在前,
stmp.push_back(s[i--]); // 当 i<0时 s[i]超出范围,编译出错。
reverse(stmp.begin(), stmp.end());
if(!st.empty())
stmp.push_back(' ');
st.append(stmp);
}
s = st;
}
};