ZigZag Conversion
1、原题
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"
.
2、题意解析
这道题的大意是给我们一个字符串,让我们根据其给的行数对其进行锯齿形化的排列,正如上面的例子,一个字符串PAYPALISHIRING,然后要分成三行,就成为了题目中呈现出来的样式,然后再根据横行来生成一个新串,目标很明确。
我的思路是:既然最后是根据横行来进行读取的,那我们就按横行来设置字符串数组。然后获得数组后的下一个步骤就是如何填充每一行的字符串,仔细观察规则,我们可以发现,它主要分为两个部分:1、竖直向下;2、斜向上。我们就可以根据这个规则来填充字符串了。
3、代码实现
public static String convert(String s, int numRows) { if (numRows == 1) { return s; } //按照其划分的行数设置字符串数组 StringBuilder[] newStr = new StringBuilder[numRows]; //初始化 for (int i = 0; i < numRows; i++) { newStr[i] = new StringBuilder(); } //遍历传入字符串 int i = 0; while (i < s.length()) { //竖直向下部分和行数持平 for (int j = 0; j < numRows; j++) { if (i >= s.length()) { break; } newStr[j].append(s.charAt(i)); i++; } //斜向上部分是重下往上,且将最下面一行和最上面一行划分到了竖直向下部分中了 for (int k = numRows - 2; k > 0; k--) { if (i >= s.length()) { break; } newStr[k].append(s.charAt(i)); i++; } } //链接字符串 StringBuilder res = new StringBuilder(); for (int k = 0; k < numRows; k++) { res.append(newStr[k]); } //返回 return res.toString(); }