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:appstring convert(string s, int numRows); Example 1:ui
Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"
Example 2:thisInput: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI"
Explanation:codeP 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(); }