Reverse Words in a String 翻转句子的单词
原创
©著作权归作者所有:来自51CTO博客作者我想有个名字的原创作品,请联系作者获取转载授权,否则将追究法律责任
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:
/*
Input: " a b "
Output: "b a"
Expected: "b a"
void reverseWords(string &s) {
int l=0,r=s.size()-1;
int k;
while(s[l]==' ') l++;
while(s[r]==' ') r--;
if(l>r)
{
s="";
return ;
}
reverse(s,l,r);
for(int i=l;i<=r;i++)
{
while(s[i]==' ')
i++;
k=i;
while(i<=r&&s[i]!=' ')
i++;
i--;
reverse(s,k,i);
}
s=s.substr(l,r-l+1);
}
void reverse(string &str,int s,int e)
{
char temp;
for(int i=s,j=e;i<=j;i++,j--)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
}
*/
//用vector处理,从尾开始放,每次放入之前逆转
void reverseWords(string &s) {
string ans;
int i=s.size()-1;
while(i>=0)
{
while(i>=0&&s[i]==' ')
i--;
if(i<0)
break;
if(ans.size()>0)
ans+=' ';
string tmp;
for(;i>=0&&s[i]!=' ';i--)
tmp+=s[i];
reverse(tmp.begin(),tmp.end());
ans+=tmp;
}
s=ans;
}
};