美文网首页
6、ZigZag Conversion

6、ZigZag Conversion

作者: liuzhifeng | 来源:发表于2017-10-13 20:18 被阅读0次

题设

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".

要点

  • 读懂题...

首先需要理解zigzag的概念。假设字符串为0123456789。
row=3时,zigzag排列为:

0    5   9
1  4 6 8
2 3  7

row=4时,zigzag排列为:

0      6  
1   5  7
2 4    8 
3      9

即先从上到下排row个数,然后按对角线排row-2个数,依次循环,直到所有都排列完。
用一个String[rowNums]数组来维护每一行的字符。
我们可以把一竖加一斜总共 (rowNums+rowNums-2)个数看成一组。组内循环,如果i<rowNums,则填充到第i行的Stirng;否则,填充到第(2*rowNums-i-2)行。
循环处理每一组,然后把所有rowNums行的String输出即可。

    public static String convert(String s , int numRows){
        String result = ""; // 存储最终结果
        int len = s.length();
        if(numRows == 1 || numRows >= len)
            return s;
        else
        {
            // 按Z字形进行分组,groups为分组数
            int groups = (len % (2 * numRows - 2)) == 0 ? len / (2 * numRows - 2) : len / (2 * numRows - 2) + 1;
            String[] str = new String[numRows];// 存储所有字符
            for(int i = 0;i < numRows;i++)
                str[i] = "";

            int count = 0;
            for(int i = 0;i < groups;i++){
                for(int j = 0;j < 2 * numRows - 2;j++){
                    if(j < numRows) { // 竖的一列
                        str[j] += s.charAt(count);
                        count++;
                    }
                    else{
                        str[2 * numRows - 2 - j] += s.charAt(count); // 斜对角线
                        count++;
                    }
                    if(count == len)
                        break;
                }
            }
            for(int i = 0;i < numRows;i++)
                result += str[i];
        }
        return  result;
    }

相关文章

网友评论

      本文标题:6、ZigZag Conversion

      本文链接:https://www.haomeiwen.com/subject/fzltuxtx.html