天天看點

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() ==  || s == null || numRows <= ) {
            return "";
        }
        if (numRows == )
            return s;
        StringBuilder sb = new StringBuilder();
        int size =  * numRows - ;
        for (int i = ; i < numRows; i++) {
            for (int j = i; j < s.length(); j += size) {
                sb.append(s.charAt(j));
                System.out.println(sb);
                if (i !=  && i != numRows - ) {
                    int temp = j + size -  * 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, ));

    }
}