题目要求:
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 R
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"
.
所谓的ZigZag,就是这样的:(P.S:某些浏览器的高速模式可能看不到图,兼容或IE模式应该可以)
因为这是有规律的,可以用数学公式计算出下一个数组下标,这样节省了一定的空间和时间。 题目的输出是按行来拼接字符的,
因此我们可以通过逐行计算下标,拼接字符来达到目的。
实现代码:
char* convert(char* s, int numRows) { int num = strlen(s); if(numRows <=1 || num <= numRows) return s; char *result = (char *)malloc(num+1); int i,skip,index,j =0; for(i = 0; i < numRows; i++) { if(i == numRows-1) skip = 2*(numRows-1); else skip = numRows-1; index = i; while(index < num) { result[j++] = s[index]; index +=(skip-index)*2; if(i == numRows-1 || i == 0 ) skip += 2*(numRows-1); else skip += numRows-1; } } result[num] = 0; return result; }