leetcode [#6]

目录

题目

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)

1
2
3
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 text, int nRows);

convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.


解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Solution {
public String convert(String s, int numRows) {
int len = s.length();
if(len == 0) return "";
if(numRows == 1) return s;
char[] sArr = s.toCharArray();
StringBuilder[] b = new StringBuilder[numRows];
for(int k = 0; k < numRows; k++){
b[k] = new StringBuilder();
}
int piece = 2 * (numRows - 1);
for(int i = 0; i < len; i++){
if(i < numRows){
b[i].append(sArr[i]);
} else {
if (i % piece >= 0 && i % piece < numRows) {
b[i % piece].append(sArr[i]);
} else {
b[piece - i % piece].append(sArr[i]);
}
}
}
StringBuilder resBuilder = new StringBuilder();
for(int m = 0; m < numRows; m++){
resBuilder.append(b[m]);
}
return resBuilder.toString();
}
}

注意事项

  1. 按照给定的numRows,将字符串排列成锯齿状,并且按照行返回。
  2. 先处理特殊情况。
  3. 定义numRows个StringBuilder,重点在于找到每个字符应该加入的StringBuilder。对于下标满足i % piece >= 0 && i % piece < numRows范围的字符串,即锯齿中“垂直方向”的一段,依次填入b[i % piece]即可;对于下标满足i % piece >= numRows范围的字符串,即锯齿中“倾斜方向”的一段,依次填入b[piece - i % piece]即可。