# 151. Reverse Words in a String

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

For example,
Given s = “`the sky is blue`“,
return “`blue is sky the`“.

Update (2015-02-12):
For C programmers: Try to solve it in-place in O (1) space.

click to show clarification.

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.

C++ 解法一：

``````class Solution {
public:
void reverseWords(string &s) {
int storeIndex = 0, n = s.size();
reverse(s.begin(), s.end());
for (int i = 0; i < n; ++i) {
if (s[i] != ' ') {
if (storeIndex != 0) s[storeIndex++] = ' ';
int j = i;
while (j < n && s[j] != ' ') s[storeIndex++] = s[j++];
reverse(s.begin() + storeIndex - (j - i), s.begin() + storeIndex);
i = j;
}
}
s.resize(storeIndex);
}
};
``````

Java解法一：

``````public class Solution {
public String reverseWords(String s) {
int storeIndex = 0, n = s.length();
StringBuilder sb = new StringBuilder(s).reverse();
for (int i = 0; i < n; ++i) {
if (sb.charAt(i) != ' ') {
if (storeIndex != 0) sb.setCharAt(storeIndex++, ' ');
int j = i;
while (j < n && sb.charAt(j) != ' ') sb.setCharAt(storeIndex++, sb.charAt(j++));
String t = new StringBuilder(sb.substring(storeIndex - (j - i), storeIndex)).reverse().toString();
sb.replace(storeIndex - (j - i), storeIndex, t);
i = j;
}
}
sb.setLength(storeIndex);
return sb.toString();
}
}
``````

C++ 解法二：

``````class Solution {
public:
void reverseWords(string &s) {
istringstream is(s);
string tmp;
is >> s;
while(is >> tmp) s = tmp + " " + s;
if(!s.empty() && s[0] == ' ') s = "";
}
};
``````

C++ 解法三：

``````class Solution {
public:
void reverseWords(string &s) {
istringstream is(s);
s = "";
string t = "";
while (getline(is, t, ' ')) {
if (t.empty()) continue;
s = (s.empty() ? t : (t + " " + s));
}
}
};
``````

Java解法二：

``````public class Solution {
public String reverseWords(String s) {
String res = "";
String[] words = s.trim().split("\\s+");
for (int i = words.length - 1; i > 0; --i) {
res += words[i] + " ";
}
return res + words[0];
}
}
``````

Java解法三：

``````public class Solution {
public String reverseWords(String s) {
String[] words = s.trim().split(" +");
Collections.reverse(Arrays.asList(words));
return String.join(" ", words);
}
}
``````

https://discuss.leetcode.com/topic/3298/in-place-simple-solution

https://discuss.leetcode.com/topic/2742/my-accepted-java-solution

https://discuss.leetcode.com/topic/11785/java-3-line-builtin-solution

https://discuss.leetcode.com/topic/10199/5-lines-c-using-stringstream

LeetCode All in One 题目讲解汇总(持续更新中…)

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

×

Help us with donation