[LeetCode] ZigZag Conversion

来源:互联网 发布:东软医保软件客服 编辑:程序博客网 时间:2024/05/17 09:12

题目

https://leetcode.com/problems/zigzag-conversion/description/

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   NA P L S I I GY   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".

代码

1158 / 1158 test cases passed.Runtime: 46 ms
#define rint register intchar* convert(char* s, int numRows) {    if (numRows == 1) {        return s;    }    int len = strlen(s);    int *cnt = (int*) malloc(numRows*sizeof(int));    for (rint i = 0; i < numRows; i++) {        cnt[i] = 0;    }    int **line = (int**) malloc(numRows*sizeof(int*));    for (rint i = 0; i < numRows; i++) {        line[i] = (int*) malloc(len * sizeof(int));    }    int MOD = numRows + numRows - 2;// 每一组有这么多个数,以MOD为一组    for (rint i = 0; i < len; i++) {        int m = i % MOD;        if (m < numRows) {            line[m][cnt[m]++] = s[i];        } else {            int lineNum = numRows-2-(m-numRows);            line[lineNum][cnt[lineNum]++] = s[i];        }    }    char *result = (char*)malloc(len+1);    int idx = 0;    for (rint i = 0; i < numRows; i++) {        for (rint j = 0; j < cnt[i]; j++) {            result[idx++] = line[i][j];        }    }    result[idx] = 0;    for (rint i = 0; i < numRows; i++) {        free(line[i]);    }    free(line);    free(cnt);    return result;}
原创粉丝点击