leetcode 6 -- ZigZag Conversion

** 题目 **

The string “PAYPALISHIRING” is written in a zigzag pattern on a given number
of rows like this: (you may want to display this pattern in a fixed font for
better legibility)

** 题意 **

将字符串按照锯齿形(N字形)排列,然后把从上到下把所有行按从做到右的顺序组成新的字符串
ps:其实我刚开始也把题意理解错了,wr了好几次,于是乎去学长博客取经后才理解。

    关于锯齿形解释如下:

            1---------------7
            2---------6----8------------12
            3----5---------9------11
            4--------------10

大概就是这个重组模式,不要嫌弃描述太抽象,图片上传不上来,空格显示不出来,我也无奈

** 思路 **

分两个部分,一是最顶行和最底行,二是中间,分别对两个部分找规律了

** 代码 **

char* convert(char* s, int numRows) {
    char *a=(char*)malloc(sizeof(char)*(strlen(s)+1));
    int i,j,l,k=0,num=numRows*2-2;
    if(strlen(s)<=numRows || numRows==1)
    {
        return s;
    }
    for(i=0;i<numRows;i++)
    {
        if(i==0 || i==numRows-1)
        {
            j=i;
            while(j<strlen(s))
            {
                a[k++]=s[j];
                j+=num;
            }
        }
        else
        {
            j=i;
            l=num-i;
            while(j<strlen(s) || l<strlen(s))
            {
                if(j<strlen(s))
                {
                    a[k++]=s[j];
                    j+=num;
                }
                if(l<strlen(s))
                {
                    a[k++]=s[l];
                    l+=num;
                }
            }
        }
    }
    a[k]='\0';
    return a;
}

leetcode 6 -- ZigZag Conversion
https://shiyi.threebody.xyz/posts/21657.html
作者
Yi Shi
发布于
2015年6月17日
许可协议