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

分析:

同一行兩個字母相隔的距離是可以算出來的。

每一個週期的長度是 size = 2*nRows - 2,

中間行需要加多一個字母,這個字母記錄同行上一個字母的距離是 size - 2*i.

public class Solution {
    public String convert(String s, int nRows) {
        if(s==null || s.length()==0 || nRows<=0)
            return "";
        if(nRows==1)
            return s;
        StringBuilder res = new StringBuilder();
        //一個折回週期的長度
        int size=2*nRows-2;
        for(int i=0; i<nRows; i++){
            //每個折回週期必然有一個數
            for(int j=i; j<s.length(); j+=size){
                res.append(s.charAt(j));
                //如果不是第0行和最後一行,則中間還要加一個數,距離爲size-2*i
                if(i!=0 && i!=nRows-1 && j+size-2*i<s.length())
                    res.append(s.charAt(j+size-2*i));
            }
        }
        return res.toString();
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章