问题:
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 text, int nRows);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.
其实就是将字符串按锯齿的形式进行整理后,按顺序读出来。
将人写这种字符串的方式,用代码表现一下即可。
代码示例:
public class Solution {
public String convert(String s, int numRows) {
if(s == null) {
return null;
}
if (numRows <= 1) {
return s;
}
int len = s.length();
//为了速度比较快,采取空间换时间的方法
//分配数组存储结果的位图
char[][] temp = new char[numRows][len];
for (int i = 0; i < numRows; ++i) {
for (int j = 0; j < len; ++j) {
temp[i][j] = '\0';
}
}
char[] sChar = s.toCharArray();
int rowIndex = 0;
int columnIndex = 0;
//zigFlag为true,表示在处理锯齿的斜线部分
boolean zigFlag = false;
for (int i = 0; i < len; ++i) {
temp[rowIndex][columnIndex] = sChar[i];
if (!zigFlag) {
//正常形式,竖着写,增加行号即可
if (rowIndex + 1 < numRows) {
++rowIndex;
} else {
--rowIndex;
++columnIndex;
zigFlag = true;
}
continue;
}
//处理锯齿部分,就是斜着写,坐标处理一下就行
if (rowIndex - 1 >= 0 && columnIndex + 1 < len) {
--rowIndex;
++columnIndex;
} else {
zigFlag = false;
++rowIndex;
}
}
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < numRows; ++i) {
for (int j = 0; j < len; ++j) {
if (temp[i][j] != '\0') {
sb.append(temp[i][j]);
}
}
}
return sb.toString();
}
}
当然,从最终的输出结果来看,完全可以忽略斜线的概念,只需要关注行号的变化,
每一行顺序添加字符即可。
class Solution {
public String convert(String s, int numRows) {
if (s == null || s.length() <= numRows || numRows == 1) {
return s;
}
String[] rows = new String[numRows];
for (int i = 0; i < numRows; i++) {
rows[i] = "";
}
int loc = 0;
boolean down = false;
for (int i = 0; i < s.length(); i++) {
rows[loc] = rows[loc].concat(String.valueOf(s.charAt(i)));
if (loc == 0 || loc == numRows - 1) {
down = !down;
}
loc += down ? 1 : -1;
}
String ans = "";
for (String row : rows) {
ans = ans.concat(row);
}
return ans;
}
}