ZipZag这个问题关键就在于找到一个周期是2*numRows-2,然后就可以很方便的解决问题了。为了可以更容易理解,我这里定义了一个指针数组,用于标记每一行的起始位置(如果要更高的性能,这里可以在后面的遍历的时候直接计算)
Code:
#include<stdlib.h>
#include<string.h>
#include<stdlio.h>
char* convert(char* s, int numRows) {
if(numRows==1){
return s;
}
char** sarr=(char**)malloc(sizeof(char*)*numRows);
int sLength=strlen(s);
char* retarr=(char*)malloc(sizeof(char)*(sLength+1));
memset(retarr,'\0',sizeof(char)*(sLength+1));
int periodLength=2*numRows-2;
int numOfPeriod=sLength/periodLength;
int periodLeft=sLength%periodLength;
*sarr=retarr;
int periodExistCount=+2*numOfPeriod;
for(int i=1;i<numRows;i++){
if(i==1){
*(sarr+i)=*(sarr+i-1)+numOfPeriod+(periodLeft<1?0:1);
}
else{
if(periodLeft<i){
*(sarr+i)=*(sarr+i-1)+periodExistCount;
}
else if(periodLeft<2*numRows-i){
*(sarr+i)=*(sarr+i-1)+periodExistCount+1;
}
else{
*(sarr+i)=*(sarr+i-1)+periodExistCount+2;
}
}
}
int row=0;
int step=1;
for(int i=0;i<sLength;i++){
*((*(sarr+row)))=*(s+i);
(*(sarr+row))++;
row+=step;
if(row==numRows){
row-=2;
if(row<0)row=0;
step=-1;
}
else if(row<0){
row+=2;
if(row==numRows)
row=numRows-1;
step=1;
}
}
return retarr;
}
阿里云最高¥2000云产品通用代金券领取地址:https://chuangke.aliyun.com/invite?userCode=aglut9wz
阿里云移动端专享9折折扣码