翻转字符串

翻转字符串

题目1:翻转单词顺序。

输入一个英文句子,翻转句子中的单词顺序,但单词内字符的顺序不变。

思路:第一步翻转句子中所有字符,第二步翻转每个单词中的字符的顺序。

参考代码:

root@gt:/home/git/Code# ./a.out student. a am i
root@gt:/home/git/Code# cat reverse.c #include <stdio.h> void flip(char* p1,char* p2)
{
    if(p1 == NULL || p2 == NULL)
        return;
    while(p1 < p2)
    {
        char temp = *p1;
        *p1 = *p2;
        *p2 = temp;

        ++p1;
        --p2;
    }
}

char* reverse(char* pdata)
{
    if(pdata == NULL)
        return NULL;
    char* p1 = pdata;
    char* p2 = pdata;

    while(*p2 != '\0')
        ++p2;
    --p2;

    flip(p1,p2);
    p1 = p2 = pdata;
    while(*p1 != '\0')
    {
        if(*p1 == ' ')
        {
            ++p1;
            ++p2;
        }
        else if(*p2 == ' ' || *p2 == '\0')
        {
            flip(p1,--p2);
            p1 = ++p2;
        }
        else
            ++p2;
    }
    return pdata;
}

int main()
{
    char pdata[] = {'i',' ','a','m',' ','a',' ','s','t','u','d','e','n','t','.','\0'};
    char* res = reverse(pdata);
    printf("%s\n",res);
    return 0;
}

题目2:左旋转字符串。

字符串的左旋转操作是把字符串的若干个字符转移到字符串的尾部。实现一个函数,例如输入”abcdef”和2,输出”cdefab”。

思路:先把”ab”旋转”ba”,再把”cdef”旋转”fedc”,再把”bafedc”旋转”cdefab”.

参考代码:

root@gt:/home/git/Code# ./a.out cdefgba
root@gt:/home/git/Code# cat leftReverse.c #include <stdio.h> void flip(char* p1,char* p2)
{
    if(p1 == NULL || p2 == NULL)
        return;
    while(p1 < p2)
    {
        char temp = *p1;
        *p1 = *p2;
        *p2 = temp;

        ++p1;
        --p2;
    }
}

char* leftReverse(char* pdata,int len,int n)
{
    if(pdata == NULL)
        return NULL;
    if(len > 0 && n >0 && n < len)
    {
        char* pA1 = pdata;
        char* pA2 = pdata + n - 1;
        char* pB1 = pdata + n;
        char* pB2 = pdata + len - 1;

        flip(pA1,pA1);
        flip(pB1,pB2);
        flip(pA1,pB2);
    }
    return pdata;
}

int main()
{
    char pdata[] = {'a','b','c','d','e','f','g','\0'};
    char* res = leftReverse(pdata,sizeof(pdata)/sizeof(char) - 1,2);
    printf("%s\n",res);
    return 0;
}

    原文作者:ailx10
    原文地址: https://zhuanlan.zhihu.com/p/34657489
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞