topic:
/**Title: 6. Zigzag Transformation (Title address: https://leetcode-cn.com/problems/zigzag-conversion/description/ )
* Arrange the string "PAYPALISHIRING" in a zigzag into a given number of lines :
* P A H N
* APLSIIG
* Y I R
* Then read characters from left to right, line by line: "PAHNAPLSIIGYIR"
* Example 1:
* Input: s = "PAYPALISHIRING", numRows = 3
* Output: "PAHNAPLSIIGYIR"
* Example 2:
* Input: s = "PAYPALISHIRING", numRows = 4
* Output: "PINALSIGYAHRPI"
* Explanation:
* P I N
* A LS IG
* YA HR
* P I
*/
A simple method is used, which is the easiest to implement and easier to understand. My idea is:
my code:
#include<stdio.h> #include<stdlib.h> #include<string.h> /**Title: 6. Z-shape transformation * Zigzag the string "PAYPALISHIRING" into the given number of lines: * P A H N * A P L S I I G * Y I R * Then read characters line by line from left to right: "PAHNAPLSIIGYIR" * Example 1: * Input: s = "PAYPALISHIRING", numRows = 3 * output: "PAHNAPLSIIGYIR" * Example 2: * Input: s = "PAYPALISHIRING", numRows = 4 * output: "PINALSIGYAHRPI" * explain: * P I N * A L S I G * Y A H R * P I */ char* convert(char* s, int numRows) { char flag = '#'; int length = strlen(s); int nz = 2*numRows - 2; int nx = length/nz + ((length%nz>0)?1:0); //printf("%d, %d, %d, %d\n",length,numRows,nx,nz); printf("Length of \"%s\" is %d.\n",s,length); int nz2 = nz + 1; int L = nz2 * nx; char *str = malloc(sizeof(char)*(L+1)); int i, ix, iz; for(i=0;i<length;i++) { ix = i/nz; iz = i%nz; str [ix * nz2 + iz] = s [i]; } for(i=0;i<nx-((length%nz>0)?1:0);i++) { str[i*nz2+nz] = flag; } for(i=nz2*(nx-((length%nz>0)?1:0))+length%nz;i<L;i++) { str[i] = flag; } str [L] = '\ 0'; printf("Length of \"%s\" is %d.\n",str,L); char *out = malloc(sizeof(char)*length); int offset = numRows-1, j, iout=0, id; while(offset>=0){ for(i=0;i<nx;i++) { id = i * nz2 + numRows -1; if(offset!= 0 && str[id - offset] != flag) out[iout++] = str[id - offset]; if(offset!= 0 && str[id + offset] != flag) out[iout++] = str[id + offset]; if(offset== 0 && str[id] != flag) out[iout++] = str[id]; } offset --; } out[length] = '\0'; printf("Length of \"%s\" is %d.\n",out,strlen(out)); return out; } int main(int argc, char **argv) { char *str = "123456789abcdefg"; int numRows = 2; printf(" Input: %s\nOutput: %s\n",str,convert(str, numRows)); return 1; }
Test Results:
D:\test>gcc leetcode6.c D:\test>a.exe Length of "abcdefghijklmnopqr" is 18. Length of "abcdefghij#klmnopqr###" is 22. Length of "akbjlcimdhnregoqfp" is 18. Input: abcdefghijklmnopqr Output: akbjlcimdhnregoqfp
another one:
char *str = "123456789abcdefg"; int numRows = 2; Length of "123456789abcdefg" is 16. Length of "12#34#56#78#9a#bc#de#fg#? is 24. Length of "13579bdf2468aceg" is 16. Input: 123456789abcdefg Output: 13579bdf2468aceg