LeetCode-6 N字形变换

139 阅读1分钟

题目

将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。 比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:

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

之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"

示例 2:

输入: s = "PAYPALISHIRING", numRows = 4
输出: "PINALSIGYAHRPI"
解释:
P     I    N
A   L S  I G
Y A   H R
P     I

题目分析

本题为找规律题目,可以观察到图形是按照一个周期在重复填充,图片的红色部分即为一个周期。 每个循环的周期字母数为:cycle = 2*numRows-2

image.png

首尾两行的字母为: index = i+cycle

中间部分都由两个字母组成,分别为:index = i+cycle*n ;index = index + cycle -i

编码

    public String convert(String s, int numRows) {
        if (numRows == 1)
            return s;
        StringBuilder ret = new StringBuilder();
        int n = s.length();
        int cycle = 2 * numRows - 2;
        for (int i = 0; i < numRows; i++) {

            for (int j = 0; j + i < n; j += cycle) { //每次加一个周期
                ret.append(s.charAt(j + i));
                if (i != 0 && i != numRows - 1 && j + cycle - i < n) //除去第 0 行和最后一行
                    ret.append(s.charAt(j + cycle - i));
            }
        }
        return ret.toString();
    }

时间复杂度:O(n),把每个字符遍历了 1 次,两层循环内执行的次数是字符串的长度。

空间复杂度:O(n),保存字符串。