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 s, int numRows); Example 1:
Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"
Example 2:Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI"
Explanation:P I N A L S I G Y A H R P I
一般的问题属于给结果,需要找到那种状态,这种表述不太准确且模糊。
而这类问题属于给出给出所有条件,让你输出结果,难点在于找到规律,经验是一般刨除编程大脑告诉你怎么弄就怎么弄。
这道题如果是现实中的话就是把数字按规律写出来。问题就可以转化为把字符放到合适的排里。
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();
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。