leetcode zigzag conversion C语言实现

发布时间:2019-08-06 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了leetcode zigzag conversion C语言实现脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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的排列规律:第一行和最后一行都是没有斜边的,间隔是(2*nRows - 2)其中nRows是总行数;

有斜边的中间几行其实也有规律,斜边上的数字到左边那个列的距离是(2nRows - 2 - 2row)其中row是当前行的行号。

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

char *convert(char *s, int nRows)
{
    if ((NULL == s) | (nRows < 1))
    {
        return NULL;
    }
    // + 1 for NIL or '' in the end of a string
    const size_t len = strlen(s);
    char* output = (char*) malloc(sizeof(char) * ( len + 1));
    char* head = output;
    output[len] = '';
    if ( 1 == nRows )
    {
        return strcpy(output, s);
    }
    for (int row = 0; row < nRows; ++row)
    {
        //processing row by row using (2nRows-2) rule
        for (unsigned int index = row; index < len; index += 2*nRows-2)
        {
            // if it is the First row or the last row, then this is all
            *output++ = s[index];
            // otherwise, there are middle values, using (2nRows-2-2*row) rule
            // notice that nRows-1 is the last row
            if ( (row>0)&(row<nRows-1) & ((index+2*nRows - 2 - 2*row) < len))
            {
                *output++ = s[index+2*nRows - 2 - 2*row];
            }
        }
    }
    return head;
}
int main()
{
    char* input = (char*)"A";
    int rows = 1;
    char* output = convert(input, rows);
    if (NULL != output)
    {
        printf("input: %s;  output: %sn", input, output);
        free(output);
    }else
    {
        printf("emptyn");
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的leetcode zigzag conversion C语言实现全部内容,希望文章能够帮你解决leetcode zigzag conversion C语言实现所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。