Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
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.
思路:翻转的思路是很清楚的,就是卡在空格上了。结果专门先循环一遍来去掉空格。
注意,必须改变指针中所对应的值才能改变字符串。
void reverse(char * s, char * e) { while(s < e) { char tmp = *s; *s = *e; *e = tmp; s++; e--; } } void reverseWords(char *s) { //先专门处理空格 char * p = s; char * snew = s; while(*p != '