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.
- 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.
例如:
输入字符串 s = "the sky is blue
",
返回 "blue is sky the
".
如用 C 语言实现,则要求空间复杂度为 O(1).
说明:
word 定义为不含空格的字符序列。
输入字符串中可以首尾可以有空格,但翻转后的字符串首尾不能含空格。
输入字符串的 word 中间可能有多个空格,但翻转后的字符串 word 间只能有一个空格。
分析:
先翻转每个 word,再翻转整个字符串,或者反过来。
翻转前先去掉字符串尾可能存在的空格,然后翻转每个 word,再翻转整个字符串,最后去掉多余的空格。
<pre name="code" class="cpp">void reverseWords(char *s) {
char *pstart = NULL, *pend = NULL;
char temp = 0;
int hasword = 0;
char *pwordstart = s;
char *ps = s;
if(!s) /*空*/
return;
while(*ps)
{
if(*ps != ' ') /*word*/
{
hasword = 1;
pstart = ps++; /*一个word开头*/
while(*ps && *ps != ' ')
{
++ps;
}
pend = ps-1; /*一个word结尾*/
for(; pstart < pend; ++pstart,--pend) /*翻转一个word*/
{
temp = *pstart;
*pstart = *pend;
*pend = temp;
}
}
else
{
++ps;
}
}
if(hasword == 0)
{
*s = '\0';
return;
}
while(*--ps == ' '); /*查找非空字符串结尾*/
*++ps = '\0';
for(pstart = s, pend = ps-1; pstart < pend; ++pstart,--pend)
{
temp = *pstart;
*pstart = *pend;
*pend = temp;
}
ps = s;
while(*pwordstart)
{
if(*pwordstart == ' ' && *(pwordstart+1) == ' ') /*连着空格,不赋值*/
{
++pwordstart;
}
else if(*pwordstart == ' ' && *(pwordstart+1) == '\0')
{
break;
}
else
{
*ps = *pwordstart;
++pwordstart;
++ps;
}
}
*ps = '\0';
return;
}