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 RAnd 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"
.
这个题目看完以后我猜大部分人还是没搞明白题目到底想干啥,我当时也没搞明白,主要原因还是例子给的有点少,好,既然他例子给的少,那我们自己再举几个栗子……
假设输入字符串为“ABCDEFGHIJKLMNOPQRSTUVWXYZ”
那么当nRow = 3时:
A E I M Q U Y
BDFHJLNPRTVXZ
C G K O S W
那么当nRow = 4时:
A G M S Y
B FH LN RT XZ
CE IK OQ UW
D J P V
那么当nRow = 5时:
A I Q Y
B HJ PR XZ
C G K O S W
DF LN TV
E M U
这下就很明白了,代码的实现不是很难,只要控制好边界条件即可。我的思路也很简单,按照当前字符串的字符顺序填入二维数组中,然后再去便利二维数组……感觉时间复杂度上还是控制的不太好,以后有了更好的方法再更新吧……
public class ZigZagConversion {
public String convert(String s, int numRows) {
if (numRows == 1)
return s;
int len = s.length();
int times = len / (numRows + numRows - 2);
int tailLen = len % (numRows + numRows - 2);
StringBuilder stringBuilder = new StringBuilder("");
char zzArr[][] = new char[numRows][(times + 1) * (numRows - 1)];
int k = 0;
boolean tag = false;
boolean clo = true;
boolean dig = false;
for (int i = 0; i < (times + 1) * (numRows - 1);){
if (clo){
for (int j = 0; j < numRows;){
if (k < s.length())
zzArr[j][i] = s.charAt(k++);
j++;
if (j < numRows -1){
clo = true;
dig = false;
}
if (j == numRows - 1){
clo = false;
dig = true;
}
}
}
if (dig){
for (int j = numRows - 1; j > 0;) {
j--;
i++;
if (j > 0 & k < s.length())
zzArr[j][i] = s.charAt(k++);
if (j > 0){
clo = false;
dig = true;
}
if (j == 0){
clo = true;
dig = false;
}
}
}
if (k == s.length())
break;
}
for (int i = 0; i < zzArr.length; i++){
for (int j = 0; j < zzArr[i].length; j++){
if (zzArr[i][j] >= '!' && zzArr[i][j] <= '~')
stringBuilder.append(zzArr[i][j]);
}
}
return stringBuilder.toString();
}
}