zigzag pattern 即之字型,字母“Z”型,convert函数要求将一个Z字形按列读取的字符串转换为按行读取的字符串。
基本思路是按行顺序读取并存入结果字符串,总行数为min(nRows,len),nRows为Z字的行数,len为源字符串的总长度。
下面用图来说明:
行数k=1,nRows时,读取第一个字符后,下一个字符与当前字符在源字符串中的距离为step = 2(nRows-1),依次重复
1<k<nRows时,读取第一个字符后,下一个字符与当前字符在源字符串中的距离为step1 = 2(nRows-k),下一个字符与下下个字符在源字符串中的距离为step2 = 2(k-1),如此以step1,step2进行重复
char* convert(char* s, int numRows) {
int len = strlen(s);
int num = 0, i, step1,step2,step, index;
char *res = (char *)malloc((len+1)*sizeof(char));
for(i = 1; i <= numRows && i <= len; ++ i){
index = i;
if(i == 1 || i == numRows){
step = 2 * numRows - 2;
while(index <= len){
res[num] = s[index-1];
num ++;
index += step;
}
}else{
step1 = 2*(numRows - index);
step2 = 2*(index - 1);
while(index <= len){
res[num] = s[index-1];
num ++;
index += step1;
if(index <= len){
res[num] = s[index-1];
num ++;
}
index += step2;
}
}
}
res[len] = '\0';
return res;
}