006 - 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   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".


蛇形图案,就像ffmpeg的那个图案类似,比如1, 2, 3, 4, 5, 6, 7,8,9,10按4个一列排,如下所示

1            7

2        6  8

3    5      9

4            10

规律就是: n个一列,则间隔为2n - 2 = x

第一排 +0 +x +0 +x....

第二排 +1 +(x-1) +1 +(x-1)

...

最后一排+(x-1) +0 +(x-1) +0

#define LEFT	0
#define RIGHT	1
char* convert(char* s, int numRows) 
{
	if (numRows == 1) return s;
	int i, rowo, magic = 2 * numRows - 2;
	int k = 0, left, right, past = RIGHT, prow = -1;
	int slen = strlen(s);
	char *tmp = (char *)calloc(sizeof(char), slen + 1);
	for (rowo = 0; rowo < numRows; rowo++) {
		int row = rowo;
		left = magic - 2 * row;
		right = 2 * row;
		past = RIGHT;
		while (row < slen) {
			if (row != prow) tmp[k++] = s[row];
			prow = row;
			if (past == RIGHT) {
				past = LEFT;	
				row += left;
			} else {
				past = RIGHT;
				row += right;
			}
		}
	}
	return tmp;
}



你可能感兴趣的:(006 - ZigZag Conversion)