Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue",
return "blue is sky the".
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Could you do it in-place without allocating extra space?
class Solution { //每个单词先反转,最后整体反转
public:
void reverseWords(string &s) {
int left = 0;
for (int i = 0; i <= s.size(); ++i) {
if (i == s.size() || s[i] == ‘ ‘) {
reverse(s, left, i - 1);
left = i + 1;
}
}
reverse(s, 0, s.size() - 1);
}
void reverse(string &s, int left, int right) {
while (left < right) {
char t = s[left];
s[left] = s[right];
s[right] = t;
++left; --right;
}
}
};