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".


分析

其實只有一個難點,只有發現了規律就很簡單了。第一行和最後一行都是沒有斜邊的,間隔是(2*nRows - 2)其中nRows是總行數;

有斜邊的中間幾行其實也有規律,斜邊上的數字到左邊那個列的距離是(2*nRows - 2 - 2*row)其中row是當前行的行號。

明白這兩個規律就行了。


C語言代碼 注意就算s只有一行,也不能return s; 要malloc 內存 strcpy 再返回。

#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 '\0' 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] = '\0';

    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: %s\n", input, output);
        free(output);
    }else
    {
        printf("empty\n");
    }

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章