Topic:
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 NA p L S i i GY 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".
Test instructions
Rearranges the string by column in the given format, followed by rows to return the new string.
Algorithm Analysis: We take the character in the string ordinal to arrange the analysis
* One: 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 ...
* Did you find the rules? 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 a simple situation and see if we can find a pattern. This topic, we write to these special cases.
* We find the following rules, here we assume we are divided into M-rows:
* 1 row I starting from I
* 2 the interval of two digits of row i is 2 (i-1), 2 (m-i) alternating
The code is as follows:
public class Solution {public string convert (string s, int numrows) { string result = ""; if (numrows = = 1) { return s; } for (int i = 0; i < numrows; i++) { int j = i; Boolean flag = true;//Toggles between two intervals via flag while (J < S.length ()) { result+= (S.charat (j)); if (i = = 0 | | i = = numRows-1)//Start and end lines are spaced between two numbers is 2 (i-1) J + = 2 * (numRows-1); else { if (flag) { J + = 2 * (numRows-1-i); Flag = false; } else { J + = 2 * i; Flag = true; }}} return result;} }
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode][java] ZigZag Conversion