LeetCode-Problem 6:字符串Z字形回转

实现一个将字符串进行指定行数的转换的函数:
将字符串 “PAYPALISHIRING” 以Z字形排列成给定的行数:(下面这样的形状)
之后按逐行顺序依次排列:”PAHNAPLSIIGYIR”

P   A   H   N
A P L S I I G
Y   I   R

算法思想:

我们先构建一个数组,数组高度为numRows。根据题解,我们可以得到数组中每”两列”是一个循环。

第一列,只增加i,每次增加1
第二列,i每次减1,同时j加1

算法实现

public static String convert(String s, int numRows) {
        if (numRows <= 1) {
            return s;
        }
        int w = s.length() % 2== 0 ? s.length() / 2: s.length() / 2 + 1;
        char[][] chars = new char[numRows][w];
        int j = 0, i = 0;
        int pos = 0;
        while (pos < s.length()) {
            //第一列,只增加i值,每次增加1
            while (i < numRows) {
                if (pos >= s.length()) {
                    break;
                }
                chars[i][j] = s.charAt(pos);
                i++;
                pos++;
            }
            i = numRows - 1;
            //第二列,i值每次减1,同时j每次增加1
            while (i >= 1) {
                if (pos >= s.length()) {
                    break;
                }
                i = i - 1;
                j = j + 1;
                chars[i][j] = s.charAt(pos);
                pos++;
            }
            i = 1;
        }
        StringBuilder sb = new StringBuilder();
        for (int m = 0; m < numRows; m++) {
            for (int n = 0; n < w; n++) {
                if ((int) chars[m][n] != 0) {
                    sb.append(chars[m][n]);
                }
            }
        }
        return sb.toString().trim();
    }

猜你喜欢

转载自blog.csdn.net/kangkanglou/article/details/79851419