#6 LeetCode——ZigZag Conversion

Z字型准换

例如输入字符串:”ABCDEFGHIJKLMN”
输入n = 3,转换为:

A E I M
BDFHJLN
C G K  

输出为:”AEIMBDFHJLNCGK”



输入n = 4,转换为:

A  G  M
B FH LN
CE 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;
        }
    }
}


点赞