6. 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"
.在这个地方,leetcode也只是举了一个例子,如果有对zigzag不熟悉的,可以自己去百度资料看一下,这里我想说的是,我们的每一行每两个字符间隔的宽度是和总共的字符的行数有关的,话不多说,还是直接贴代码
char* convert(char* s, int numRows) {
int n=strlen(s);
int i,j,step,k,temp;
char *st;
if(numRows<=1||n<numRows)
return s;
step=(numRows-1)*2;
st=malloc(sizeof(char)*(n+1));
st[n]='\0';
for(i=k=0;i<numRows;i++){
temp=(numRows-i-1)*2;
for(j=i;j<n;j+=step){
st[k++]=s[j]
if( i > 0 && i < numRows - 1 && j + temp < n )
st[k++] = s[j+temp];
}
}
}