# 186. Reverse Words in a String II

Given an input string __ , reverse the string word by word.

Example:

``````Input:  ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
``````

Note:

• A word is defined as a sequence of non-space characters.
• The input string does not contain leading or trailing spaces.
• The words are always separated by a single space.

Follow up: Could you do it  in-place  without allocating extra space?

``````class Solution {
public:
void reverseWords(vector<char>& str) {
int left = 0, n = str.size();
for (int i = 0; i <= n; ++i) {
if (i == n || str[i] == ' ') {
reverse(str, left, i - 1);
left = i + 1;
}
}
reverse(str, 0, n - 1);
}
void reverse(vector<char>& str, int left, int right) {
while (left < right) {
char t = str[left];
str[left] = str[right];
str[right] = t;
++left; --right;
}
}
};
``````

``````class Solution {
public:
void reverseWords(vector<char>& str) {
reverse(str.begin(), str.end());
for (int i = 0, j = 0; i < str.size(); i = j + 1) {
for (j = i; j < str.size(); ++j) {
if (str[j] == ' ') break;
}
reverse(str.begin() + i, str.begin() + j);
}
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/186

Reverse Words in a String III

Reverse Words in a String

Rotate Array

https://leetcode.com/problems/reverse-words-in-a-string-ii/

https://leetcode.com/problems/reverse-words-in-a-string-ii/discuss/53851/Six-lines-solution-in-C%2B%2B

https://leetcode.com/problems/reverse-words-in-a-string-ii/discuss/53775/My-Java-solution-with-explanation

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation