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.
void reverseAWord(char *s,int begin,int end)
{
char tmp;
while(begin<end)
{
tmp=s[begin];
s[begin]=s[end];
s[end]=tmp;
begin++;
end--;
}
}
void reverseWords(char *s) {
int l;
int i,j;
for(i=0;s[i];)
{
if(s[i]==32)
{
if(s[i+1]==32 || i==0 || s[i+1]=='\0')
for(j=i;s[j];j++) {s[j]=s[j+1];i=0;}
else i++;
}
else i++;
}
l=strlen(s);
for(i=0;i<l;)
{
if(s[i]==' ') i++;
j=i;
while(s[i] && s[i]!=' ')
{
i++;
}
reverseAWord(s,j,i-1);
}
reverseAWord(s,0,l-1);
}
先去掉多余的空格,然后逐个单词翻转,再将整个句子翻转即可。
ABC XYZ ——>CBA ZYX——>XYZ ABC