[LeetCode]6. ZigZag Conversion

The string “PAYPALISHIRING” is written in a zigzag pattern on a givennumber of rows like this: (you may want to display this pattern in afixed 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 givena 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();
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理