分类: C/C++
2008-05-25 21:35:51
原题:
以单词为最小单位翻转字符串
Write the function String reverseStringWordByWord(String input) that reverses
a string word by word. For instance,
reverseStringWordByWord("The house is blue") --> "blue is house The"
reverseStringWordByWord("Zed is dead") --> "dead is Zed"
reverseStringWordByWord("All-in-one") --> "All-in-one"
面试系列4种的实现,比较费空间,因为多申请了一段空间来保存结果。
在看了其他高手的实现后,发现可以不用申请空间,并且循环的次数更少,也可以实现相同的效果。
大体思路是:
原字符串: The house is blue
先翻转整个字符串-> eulb si esuoh ehT
再翻转单个单词。
代码:
/********************************************************************
created: 2006/06/16
filename: C:\Documents and Settings\Administrator\桌面\flwo\reverse2.c
file path: C:\Documents and Settings\Administrator\桌面\flwo
file base: reverse
file ext: c
author: A.TNG
version: 0.0.1
purpose: 以单词为最小单位翻转字符串-2 优化版
Write the function String reverseStringWordByWord(String input)
that reverses a string word by word. For instance,
reverseStringWordByWord("The house is blue") --> "blue is house The"
reverseStringWordByWord("Zed is dead") --> "dead is Zed"
reverseStringWordByWord("All-in-one") --> "All-in-one"
参考其他高手的思路:
先翻转整个字符串-> eulb si esuoh ehT
再翻转单个单词。
*********************************************************************/
#include
#include
#include
#define REVERSE_WORD(p1, p2) while (p1 <= p2) \
{ \
char ch; \
ch = *p1; *p1 = *p2; *p2 = ch; \
p1++; p2--; \
}
/*
* name: reverse_src_word_by_word
* params:
* des [out] 输出字符串, des 指向实现申请的空间
* src [in] 输入字符串,需要处理的字符串
* return:
* 处理完成后的 des 指针
* notes:
* 以单词为最下单位翻转字符串
* 优化: 先翻转整个字符串,再翻转单个单词
*
* author: A.TNG 2006/06/16 10:37
*/
char * reverse_str_word_by_word2(char *src)
{
char *p1, *p2;
int n_src_len;
if (NULL == src)
return NULL;
/* 先把整个字符串翻转一次 */
n_src_len = strlen(src);
p1 = src; p2 = src + n_src_len - 1;
REVERSE_WORD(p1, p2);
#if 0
while (p1 <= p2)
{
/* 交换头字符和尾字符 */
char ch;
ch = *p1; *p1 = *p2; *p2 = ch;
p1++; p2--;
}
#endif
/* 再翻转单个单词 */
p1 = src; p2 = p1;
while ('\0' != *p2)
{
if (' ' == *p2)
{
char *p;
p = p2 - 1;
REVERSE_WORD(p1, p);
#if 0
while (p1 <= p)
{
char ch;
ch = *p1; *p1 = *p; *p = ch;
p1++; p--;
}
#endif
p2++;
p1 = p2;
}
else
{
p2++;
}
}
/* 翻转最后一个单词 */
p2--;
REVERSE_WORD(p1, p2);
#if 0
while (p1 <= p2)
{
char ch;
ch = *p1; *p1 = *p2; *p2 = ch;
p1++; p2--;
}
#endif
return src;
}
/*
* name: main
* params:
* none
* return:
* none
* notes:
* none
*
* author: A.TNG 2006/06/16 10:37
*/
int main()
{
// char src[] = " All-in-one ";
// char src[] = "The house is blue";
char src[] = "Zed is dead";
(void) reverse_str_word_by_word2(src);
printf("*****%s*****\n", src);
system("PAUSE");
}