LeetCode 之 ZigZag Conversion — C 实现

来源:互联网 发布:qq聊天软件 编辑:程序博客网 时间:2024/05/16 06:56

ZigZag Conversion

 

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


字符串 "PAYPALISHIRING"  按照给定的行写成如下 Z 字形:

P   A   H   NA P L S I I GY   I   R

然后按行读取为 "PAHNAPLSIIGYIR"

完成如下带有字符串和给定行的转换函数。

string convert(string text, int nRows);

convert("PAYPALISHIRING", 3)  应该返回 "PAHNAPLSIIGYIR".

分析:

如果字符串个数小于给定行数,则输出只有一列。否则,对每个 Z 字形分成一个单元,按行计算每个字符对应新字符串的位置,除了第一行和最后一行,每个单元每次每行都要计算两个字符位置,注意每行第二个字符存在性的判断。


char* convert(char* s, int numRows) {    char *pret = NULL, *temp = NULL;    int icharLen = 0;    int ilen = 0, irow = 0, inum = 0;    int icount = 0, iunit;        if(NULL == s || numRows == 0) /*空字符串行数不合法*/        return NULL;            icharLen = strlen(s);    pret = (char *)malloc(icharLen + 1);    if(1 == numRows || numRows >= icharLen) /*输出为一行或者输出行数大于等于字符个数*/    {        temp = pret;        while(*temp++ = *s++);        return pret;    }            iunit = 2*numRows-2; /*平均每单元字符个数*/        for(; irow < numRows; ++irow)    {       for(inum = 0; inum*iunit + irow < icharLen; ++inum)       {           pret[icount++] = s[inum*iunit + irow];           if(irow != 0 && irow != iunit/2)/*不是首尾两行,每次需要计算两个字符位置*/           {               if(inum*iunit + iunit - irow < icharLen)/*判断第二个字符是否存在*/               {                   pret[icount++] = s[inum*iunit + iunit - irow];               }           }       }    }    pret[icharLen] = '\0';    return pret;}

0 0