The string is "PAYPALISHIRING"
written with 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 on line:"PAHNAPLSIIGYIR"
Write the code that would take a string and make this conversion given a number of rows:
String convert (string text, int nRows);
convert("PAYPALISHIRING", 3)
should return "PAHNAPLSIIGYIR"
.
Solution: String "0123456789ABCDEF", converted to zigzag:
n=2, the string coordinate becomes the zigzag of the way:
0 2 4 6
1 3 5 7
N=3 the way to go is:
0 4 8
1 3 5) 7 9
2 6 10
N=4 the way to go is:
0 6 12
1 5 7 13
2 4 8 14
3 9 15
In addition to the number of the first and last lines without the middle form of the shape, the other has, and the end of the two lines adjacent to the index of two elements is related to the number of rows, for 2*nrows-2, according to this feature, we can sequentially find all the black elements in the position of the meta-string, Add them sequentially to the new string. The position of the red element is also regular, the position of each red element is J + 2*nrows-2-2*i, where j is the number of columns of the previous black element, and I is the current number of rows. For example, when n = 4 of the Red 5, its position is 1 + 2*4-2-2*1 = 5, the correct position of the original string. When we know the correct algorithm for the position of all the black elements and the red elements, we can add them to the new string in order at once.
classSolution { Public: stringConvertstringSintnumrows) { intSS =s.size (); if(SS <2|| NumRows <2|| SS <numrows)returns; stringRes""); intStep =2* (NumRows-1); for(inti =0; i < numrows; i++) { for(intj = i; J < SS; J + =Step) {Res+=S[j]; intmore = j + Step-2*i; if(I! =0&& I! = numrows-1&& More <ss) Res+=S[more]; } } returnRes; }};
Reference: http://www.cnblogs.com/grandyang/p/4128268.html
[Leetcode] 7. ZigZag Conversion ZigZag Conversion