# LeetCode 6：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"`.

`/** *  congratulations *  c     t     o *  o   a u   i n *  n r   l t   s *  g     a */`

`/** *  String:     congratulations *  Row  1:     c     t     o *  Row  2:     o   a u   i n *  Row  3:     n r   l t   s *  Row  4:     g     a */`

i = 0；第1行，字符s[i] = c append给rowArray[0]，flag = 1表示下一个往下走了，row += flag向下进入第2行

i = 1；第2行，字符s[i] = o append给rowArray[1]，flag = 1，row += flag向下进入第3行

i = 2；第3行，字符s[i] = n append给rowArray[2]，flag = 1，row += flag向下进入第4行

i = 3；第4行，字符s[i] = g append给rowArray[3]，flag = -1表示下一个往上走了，row += flag向上进入了第3行

i = 4；第3行，字符s[i] = r append给rowArray[2]，flag = -1，row += flag向上进入第2行

……

Java源码

`package com.maoxiaomeng;import java.util.Arrays;/** * @author lihui * @date 2018/3/25 16:44 */public class Solution {    public String convert(String s, int numRows) {        /**         *  String:     congratulations         *  Row  1:     c     t     o         *  Row  2:     o   a u   i n         *  Row  3:     n r   l t   s         *  Row  4:     g     a         */        int len = s.length();        if (numRows <= 1 || numRows >= len) {            return s;        }        String[] rowArray = new String[numRows];        Arrays.fill(rowArray, "");                int row = 1;        int flag = 1;        for (int i = 0; i < len; ++i) {            rowArray[row - 1] += s.charAt(i);            if (row == 1) {                flag = 1;            }            if (row == numRows){                flag = -1;            }                        row += flag;        }        String ss = new String();        for (String myStr : rowArray) {            ss += myStr;        }        return ss;    }}`