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)
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”.
char* convert(char* s, int numRows) {
int i,j,k=0;
int l,n;
l=strlen(s);
char convert[10000];
convert[l]='\0';
if(numRows==1) return s;
n=2*numRows-2;
for(i=0;i<numRows;i++)
{
for(j=i;j<l;j++)
{
if( j%n==i||j%n==n-i )
{
convert[k++]=s[j];
}
}
}
return convert;
}
开始想复杂了,还设了好多flag发现只要取余就好。
本文介绍了一种将字符串以ZigZag形式排列并逐行读取的算法实现。通过示例说明如何将字符串“PAYPALISHIRING”按指定行数进行ZigZag转换,最终得到“PAHNAPLSIIGYIR”。代码实现简洁明了,使用取余运算判断字符位置。
259

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



