LeetCode 之 ZigZag Conversion — C 实现

本文详细阐述了zigzag字符串转换算法的实现过程,包括如何将字符串按照指定的行数写成Z字形,以及如何从Z字形结构中读取原始字符串。通过实例演示,帮助读者理解并掌握zigzag转换的原理。

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


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

P   A   H   N
A P L S I I G
Y   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;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值