# [Leetcode]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.

class Solution {
public:
/*algorithm
reverse whole sentence
reverse word by word
time O(n) space O(1)
*/
void reverse(string &s,int start,int len){
int i = 0,j = len-1;
while(i < j){
swap(s[start+i],s[start+j]);
i++,j--;
}
}
void reverseWords(string &s) {
//space pre-process,remove leading and trailing spaces,reduce words space to 1
int k = 0;
for(int i = 0;i < s.size();i++){
if(s[i] != ' '){
if(i&&s[i-1]==' '&&k)s[k++] = ' ';
s[k++] = s[i];
}
}
s.resize(k);

reverse(s,0,s.size());
for(int i = 0;i < s.size();){
int j = i;
while(j+1 < s.size() && s[j+1] != ' ')++j;
reverse(s,i,j-i+1);
i = j+2;
}
}
};

• 本文已收录于以下专栏：

## Reverse words in a string-leetcode

• 2014年08月30日 18:27
• 197B
• 下载

## 【LeetCode-面试算法经典-Java实现】【151-Reverse Words in a String（反转字符串中的单词）】

【152-Reverse Words in a String（反转字符串中的单词）】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题　　Given an input strin...

## [LeetCode186]Reverse Words in a String II

Given an input string, reverse the string word by word. A word is defined as a sequence of non-space...

## [leetcode]151. Reverse Words in a String

Given an input string, reverse the string word by word.For example, Given s = "the sky is blue", ret...

## LeetCode（151） Reverse Words in a String

• fly_yr
• 2015年11月01日 15:07
• 634

## [leetcode]151. Reverse Words in a String@Java解题报告

https://leetcode.com/problems/reverse-words-in-a-string/tabs/description Given an input s...

## LeetCode OJ 之 Reverse Words in a String （翻转字符串的单词）

举报原因： 您举报文章：[Leetcode]Reverse Words in a String 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)