一道经典面试题“I love china”的实现

来源:互联网 发布:sap hana数据库优势 编辑:程序博客网 时间:2024/05/23 18:08

来看一道经典的面试题,题目要求如下:

给定一个字符串“I love china”,编写程序完成以单词为单位的逆序,如“china love i”,并要求允许使用第三方变量保存数据,但可以使用辅助变量指针等。

这道题主要考察字符串的遍历查找以及分类处理,首先确定算法,我们可以这样处理字符串:

1. 将字符串整体导致:“anihc evol i”

2. 然后再次遍历字符串,将每个单词倒置:“china love i”

确定完算法后就可以用程序进行操作了,以下是程序的实现过程:

#include < stdio.h>
        #define N 32
        int swap(char *head, char *tail);
        int main()
        {
                char buff[N];
                char *head = buff,
                *tail = buff;
                //先讲尾指针定位到字符串尾部。
                While(‘\0’!= *tail)
                tail ++;
                //调用swap函数将整个字符串倒置。
                swap(buff,tail - 1);
                //主函数开始扫描遍历整个倒置后的字符串。
                while('\0' != *head)
                {
                        //查找单词头。
                        while(32 == *head)
                        head ++;
                        //找到头后将尾定位到头,开始找单词尾。
                        tail = head;
                        while(32 != *tail && '\0' != *tail)
                        tail ++;
                        //前两步找到头之后将单词倒置(因为循环结束后tail指向‘\0’,所以tail -1)。
                        swap(head,tail - 1);
                        //单词倒置后将头指向尾,为下次找单词做准备。
                        head = tail;
                }
                puts(buff);
                return 0;
        }

//swap函数,完成指定字符串倒置。

int swap(char *head, char *tail)
        {
                while(head < tail)
                        {
                                //异或法进行交换数据
                                *head ^= *tail;
                                *tail ^= *head;
                                *head ++ ^= *tail --;
                        }
        }

原创粉丝点击