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

被折叠的 条评论
为什么被折叠?



