[LeetCode]6. 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:app

string convert(string s, int numRows); Example 1:ui

Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"
Example 2:this

Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI"
Explanation:code

P I N A L S I G Y A H R P Istring

通常的問題屬於給結果,須要找到那種狀態,這種表述不太準確且模糊。
而這類問題屬於給出給出全部條件,讓你輸出結果,難點在於找到規律,經驗是通常刨除編程大腦告訴你怎麼弄就怎麼弄。
這道題若是是現實中的話就是把數字按規律寫出來。問題就能夠轉化爲把字符放到合適的排裏。it

public String convert(String s, int numRows) {
    if(numRows<=1) return s;
    ArrayList<Character>[] rows=new ArrayList[numRows];
    for(int i=0;i<numRows;i++) rows[i]=new ArrayList();
    int index=0;
    char[] array=s.toCharArray();
    for(char c:array){
        rows[Math.abs(index)].add(c);
        index++;
        if(index==numRows) index=-index+2;
    }
    StringBuilder builder=new StringBuilder();
    for(int i=0;i<numRows;i++)
        for(char c:rows[i]) builder.append(c);
    return builder.toString();
}
相關文章
相關標籤/搜索