#6 LeetCode——ZigZag Conversion

来源:互联网 发布:java socket 长链接 编辑:程序博客网 时间:2024/06/05 02:57

Z字型准换

例如输入字符串:"ABCDEFGHIJKLMN"
输入n = 3,转换为:
A E I MBDFHJLNC G K  输出为:"AEIMBDFHJLNCGK"

输入n = 4,转换为:
A  G  MB FH LNCE IK  D  J   输出为:"AGMBFHLNCEIKDJ"

输入n = 2,转换为:
ACEGIKM  BDFHJLN  输出为:"ACEGIKMBDFHJLN"

java代码为

public class Solution {    public String convert(String s, int numRows) {        if(s == null || numRows <= 0)        {            return null;        }        else if(numRows == 1)        {            return s;        }        else        {            int index = 0;            int len = s.length();            int period = numRows * 2 - 2;            char str[] = s.toCharArray();            char[] res = new char[len];                        for(int row = 0; row < numRows; row++)                {                    int i = row;                    int j = period - row;                    for( ; i < len; )                    {                        if(row == 0 || row == numRows - 1)                        {                            res[index] = str[i];                            i = i + period;                            index++;                        }                        else                        {                            res[index] = str[i];                            i = i + period;                            index++;                            if(j < len)                            {                                res[index] = str[j];                                j = j + period;                                index++;                            }                        }                    }                }            String result = new String(res);            return result;        }    }}



0 0