Posted on 2006-06-25 20:24
Enjoy Life 阅读(747)
评论(2) 编辑 收藏 引用 所属分类:
程序员面试功略
请编写一个函数来颠倒单词在字符串里出现的顺序。如:Do or do not, there is no try.转换成 .try no is there , not do or Do
这里是基于记号扫描器的函数,他是这类问题的通用性解法,需要掌握
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char src[] = "I hate you for ever, hello ";
int ReverseWords(char src[])
{
char *buffer;
int TokenReadPos, WordReadPos, WordEnd, WriteWord = 0;
TokenReadPos = strlen(src) - 1;
buffer = (char *)malloc(TokenReadPos + 2);
if(!buffer)
return 0;
while(TokenReadPos >= 0){
if(src[TokenReadPos] == ' '){
buffer[WriteWord++] = src[TokenReadPos--];/*
如果不是单词的话直接将写入buffer*/
}else{
WordEnd = TokenReadPos;
while(TokenReadPos >= 0 && src[TokenReadPos] != ' ')
TokenReadPos--;
/*
这是TokenRead已经到达了空格的位置了,所以为了输出正确WordReadPos应该加1*/
WordReadPos = TokenReadPos + 1;
/*
将这个单词copy到buffer中去*/
while(WordReadPos <= WordEnd){
buffer[WriteWord++] = src[WordReadPos++];
}
}
}
buffer[WriteWord] = '\0';
strcpy(src, buffer);
free(buffer);
return 1;
}
void main()
{
printf("%s\n",src);
ReverseWords(src);
printf("%s\n",src);
}