leetcode---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”.
解题思路是寻找输出序列的规律,可以发现,第一行和最后以后的元素的位置相隔2*nRows-2;还能发现,从上到下的元素都可以按照这个规律进行计算,从下到上的斜边元素,有另一个计算规律,要发现这个规律还不算他别简单,元素位置为j+(2n-2)-2i 其中j为当前列,i为当前行;需要注意的是i、j都是从0开始的。

package stringTest;

public class zigagConversion {
    public static String convert(String s, int numRows) {
        if (s.length() == 0 || s == null || numRows <= 0) {
            return "";
        }
        if (numRows == 1)
            return s;
        StringBuilder sb = new StringBuilder();
        int size = 2 * numRows - 2;
        for (int i = 0; i < numRows; i++) {
            for (int j = i; j < s.length(); j += size) {
                sb.append(s.charAt(j));
                System.out.println(sb);
                if (i != 0 && i != numRows - 1) {
                    int temp = j + size - 2 * i;
                    if (temp < s.length())
                        sb.append(s.charAt(temp));
                }
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String s = "012345678901234";
        // String s2=convert(s, 4);
        System.out.print(convert(s, 4));

    }
}

你可能感兴趣的:(String)