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.
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.
第一点说明我们可以按照空格分割单词。
第二点告诉我们我们需要处理输入字符串首尾的空格字符,即剔除掉首尾的空格字符。
第三点告诉我们如果单词与单词之间有多个空格字符,我们翻转的时候需要剔除多余的,保留一个。
之后执行以下翻转思想:
1、从字符串末尾处遍历。遇到非空格的字符压入栈中,即push_back到temp中储存。遇到空格或者下标<0,即执行2。
2、将temp翻转。
3、翻转后的temp即是一个单词、追加于ss之后。
循环以上。既得翻转序列。
class Solution {
public:
void reverseWords(string &s) {
string ss;
int i = s.length()-1;
while(i>=0)
{
while(i>=0&&s[i] == ' ')
{
i --;
}
if(i<0) break;
if(ss.length()!=0)
ss.push_back(' ');
string temp ;
for(;i>=0&&s[i]!=' ';i--)
temp.push_back(s[i]);
reverse(temp.begin(),temp.end());
ss.append(temp);
}
s=ss;
}
};