m*********a 发帖数: 3299 | 1 这个字符串间可能有多个空格,要把空格去掉,留一个。最前面和最后面没有空格。这
个要用到额为的空间,比如stack,不能在原来字符串操作,如果要O(n)吧?
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
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. | m*********a 发帖数: 3299 | 2 void reverseWords(char *s) {
struct strStack{
char str[80];
struct strStack *next;
};
struct strStack *root,*tmp;
root=NULL;
int i;
while (*s!='\0'){
while (*s==' ') s++;
if (*s=='\0') break;
if (root==NULL){
root=malloc(sizeof(struct strStack));
root->next=NULL;
}
else {
tmp=malloc(sizeof(struct strStack));
tmp->next=root;
root=tmp;
}
i=0;
while (*s!=' '&&*s!='\0'){
root->str[i++]=*s++;
}
root->str[i]='\0';
}
while (root){
printf("%s",root->str);
root=root->next;
if (root) printf(" ");
}
} |
|