Q6:ZigZag Conversion

6. ZigZag Conversion

官方的链接:6. ZigZag Conversion

Description :

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:

1 string convert(string text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

问题描述

 Z型转换输出转换后的字符串

思路

方法一、参考官网
这也是比较容易理解的,建立numRows个字符串,然后遍历原字符串,对数组正数和倒数,逐个把字符按照规则添加到这些字符串数组中,最后合并。

方法二、不建立数组,直接根据规则一行一行拼接字符串。
1、Z型走法,一组总共是n = numRows + numRows - 2,即n个字符
2、从第0行开始计数,记为第row行,第0行和最后一行numRows-1的规则比较好确认:n * j + row即为第row所有的字符,j从0开始,直到n * j + row临界,row行共有j个字符
3、其他行的字符,除了上面的记录字符,在不会越界的情况下,还会多一个连接的字符,这个字符的下标可以这样计算:(j + 1) * n - row,其实(j + 1) * n是下一组的开头,减去当前的行数row,即可得到下一个字符,比如上面的例子,row=1,j=0,下一组的字符是A(第一行的第2个字符)(如下图),计算出来的下标3,即P(第2行第2个字符)(如下图),合并。

[github-here]

 1 public class Q6_ZigZagConversion {
 2     public String convert(String s, int numRows) {
 3         if (numRows == 1) {
 4             return s;
 5         }
 6         int n = numRows + numRows - 2, len = s.length();
 7         StringBuilder result = new StringBuilder();
 8         for (int row = 0; row < numRows; row++) {
 9             int j = 0, headIndex = j * n + row, tailIndex = (j + 1) * n - row;
10             while (headIndex < len) {
11                 result.append(s.charAt(headIndex));
12                 j++;
13                 headIndex = j * n + row;
14                 if (row != 0 && row != numRows - 1 && tailIndex < len) {
15                     result.append(s.charAt(tailIndex));
16                     tailIndex = (j + 1) * n - row;
17                 }
18             }
19         }
20         return result.toString();
21     }
22 
23     public static void main(String[] args) {
24         Q6_ZigZagConversion s = new Q6_ZigZagConversion();
25         System.out.println(s.convert("PAYPALISHIRING", 3));
26     }
27 }
原文地址:https://www.cnblogs.com/wpbxin/p/8665045.html