leetcode 6 ZigZag Conversion

ZigZag Conversion
Total Accepted: 50923 Total Submissions: 236853

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)

P A H N
A P L S I I G
Y I R

And then read line by line: “PAHNAPLSIIGYIR”

Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);

convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.

首先我们需要了解什么ZigZag是什么样子的呐. 举个例子: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17这18个数如果按照ZigZag来排列那就应该是这个样子的:
这里写图片描述
我们现在可以发现一个规律: 第一行的元素的序号是2*nRows-2的整倍数. 在这个例子中: 0 = 0 * (2*5-2), 8 = 1 * (2*5-2), 16 = 2 * (2 *5-2). 利用这个规律我们可以把输入数据进行分组,如图:
这里写图片描述 这里写图片描述
我们发现了另一个规律,如果按行来读这些数据,实际上的读的过程可以描述为:
读每一组的第一个,然后读每一组的第二个和倒数第一个,然后读每一组的第三个和倒数第二个,然后每一组的第四个和倒数第三个… …
所以我们可以用如下方式来实现,先按序读出每一组的第一个,然后用两个指针,一个正向指针指向每一组的第二个,一个逆向指针指向最后一个,先读正向指针指的数,再读逆向指针指的数,然后正向指针往后移一个,逆向指针往前移一个… …,这个过程直道两个指针指向的是同一个数时,说明已到最末行,下次循环时,逆向指针跑到正向指针前了,此时退出循环。需要特别说明的是对于最末一组,通常元素填不满,如图中的最后一组,此时逆向指针一开始指向的不是17,而应该是23,然后我们判断23>17,所以超出范围,不进行读数,但是仍然要像其它组一样往前移一个。这样做是为了统一所有组的操作,简化程序。
另外要提一下的是,测试程序中会给出空串,或者要求行数只有1行,此时返回原串即可。

下面是完整代码:

#include <stdio.h>
#include "string.h"
#include "stdlib.h"

char* convert(char* s, int numRows) 
{
    int len = strlen(s);
    if(len == 0)
        return s;
    if(numRows == 1)
        return s;

    char *s1 = (char*)malloc((len + 1)* sizeof(char));
    int groupSize = 2 * numRows - 2;
    int numGroup;
    if(len % groupSize == 0)
        numGroup = len / groupSize;
    else
        numGroup = len / groupSize + 1;

    int firstloop = 1, f_exit = 0;
    int j = 0, index = 0;

    while(1)
    {
        for(int i = 0; i < numGroup; i++)
        {
            if(firstloop)
            {
                s1[index++] = s[i * groupSize];
            }
            else
            {
                if(i * groupSize + j > (i + 1) * groupSize - j)
                {
                    f_exit = 1;
                    break;
                }
                if(i * groupSize + j < len)
                {
                    s1[index++] = s[i * groupSize + j];

                    if(i * groupSize + j == (i + 1) * groupSize - j)
                    {
                    }
                    else if((i + 1) * groupSize - j < len)
                        s1[index++] = s[(i + 1) * groupSize - j];
                }
            }
        }
        if(f_exit)
            break;
        firstloop = 0;
        j++;
    }
    s1[index] = '\0';
    return s1;
}

int main()
{
    char s[10000];
    int numRows;

    scanf("%s", s);
    scanf("%d", &numRows);
    char *p = convert(s, numRows);
    printf("%s",p);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值