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"
如果找出规律来说不算难题。
这道是要一个String类型的字符串中的字母按照Z排序(其实是按照中心对称的N来排序),比如
String s = "helloworld"; int numRows = 4;
输出结果为 hoewrlolld
//排序的结构图如下
对应的index 对应的行数变化 int y = 0
第1行 h o 0 6 +1 -1
第2行 e w r 1 5 7 +1 -1 +1
第3行 l o l 2 4 8 +1 -1 +1
第4行 l d 3 9 +1 +1
在 y == nowRows-1 前一直+1,随后在y=0 前一直-1.
思路在代码的注释中大致分为3步和几个限制条件
class Solution {
public String convert(String s, int numRows) {
//首先判断什么时候直接输出
if(s.length() == 1 || s.length() < numRows || numRows == 1){
return s;
}
//创建对应的sb存储对应的numRows行的字符
StringBuilder [] sb = new StringBuilder[numRows];
for(int i = 0; i < numRows ; i++){
sb[i] = new StringBuilder();
}
//将对应的字符按规律放入sb中
int y = 0;
int desc = 0;
for(int i = 0; i < s.length(); i++){
if(y == 0){
desc = 1;
}
if(y == numRows-1){
desc = -1;
}
sb[y].append(s.charAt(i));
y += desc;
}
//将行的sb拼装, 注意:i的初始值为1
for(int i = 1; i < numRows; i++){
sb[0].append(sb[i]);
}
return sb[0].toString();
}
}