Problem:
The string "Paypalishiring" is written with a zigzag pattern on a given number of rows like this: (You could want to display T His-pattern in a fixed-font for better legibility) p a H- NA p L S i i GY i RAnd then-read line by line: "Pahnaplsiigyir" Write the code that would take a string and make this conversion given a number of rows:string convert (str ing text, int nRows); CONVERT ("Paypalishiring", 3) should return "Pahnaplsiigyir".
Thinking:
(1) Read the test instructions, rearrange the strings according to the "Z" shape, and then link them to the output.
(2) There is no idea of disintegration, you can enumerate a few simple examples to find the law.
A: 2 rows, 1 to N of the sort
1 3 5 7 9 ...
2 4 6 8 10 ...
Two: 3 Rows of time, 1 to n sort of
1 5 9 ...
2 4 6 8 10 ...
3 7 11 ...
Three: 4 rows of time, 1 to n sort of
1 7 13 ...
2 6 8 12 14 ...
3 5 9 11 15 ...
4 10 16 ...
Is this the law? If not found, you can continue to write 5 rows of case. Soon you'll be able to find patterns. This is a way to solve the problem. When we have a difficult problem, let's consider the simple situation and see if we can find a pattern. This topic, we have written to these special cases, we find the following law, here we assume that we are divided into M-row:
1 row I starting from I
2 The interval of two numbers in row i is 2 (i-1), 2 (m-i) alternating
Code
Class Solution {public: string Convert (string s, int nRows) { int length = S.size (); if ((nrows==1) | | | (nrows>=length)) return s; string result; for (int i=0;i<nrows;i++) { bool flag=true; int j=i; while (J<length) { Result.push_back (s.at (j)); if ((i==0) | | | (i==nrows-1)) j+=2* (nRows-1); else { if (flag) { j+=2* (nrows-i-1); Flag=false; } else { j+=2*i; flag=true; } } else }//while }//for return result; convert};
Leetcode | | ZigZag conversion Problems