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 s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I刚看题的表情
根据上题的例子,我们将一个字符串"PAYPALISHIRING"根据图形表示的方式排列,然后按我们习惯的从左到右从上到下的顺序,将字符拼接起来,连成一个字符串"PAHNAPLSIIGYIR"。
下面开始找规律,其实还是挺简单的,看见这种图形,只需要根据列数定义三个变量依次接收对应行的字符,最后再拼接成一个字符就完事了,说了这么多,看下代码就很简单了
public static void main(String[] args){
System.out.print(convert("PAYPALISHIRING", 3));
}
public static String convert(String s, int numRows) {
if (s.length() < 2 || numRows < 2) return s;
StringBuilder[] sbs = new StringBuilder[numRows];
int sbsIndex = 0;
int direction = 1;
for (int i = 0; i < s.toCharArray().length; i++) {
if (sbs[sbsIndex] == null){
sbs[sbsIndex] = new StringBuilder();
}
sbs[sbsIndex].append(s.charAt(i));
sbsIndex += direction;
direction = sbsIndex == numRows-1 ? -1 : sbsIndex == 0 ? 1 : direction;
}
StringBuilder result = new StringBuilder();
for (StringBuilder sb : sbs) {
result.append(sb == null ? "" : sb);
}
return result.toString();
}
根据代码,我们将每一行认为是一个数组,那么题目意思,无非就是往复的用每一个数组来接收给定字符串的元素了。
比如,根据题意,定义三个数组 array1 array2 array3
看图 array1 [0] = "P" array2[0] = "A" array3[0] = “Y” array2[1] = “P” array1[1] = “A” 以次类推直到循环完整个字符串。
老规矩,点击查看更多解题思路