【子串】Leetcode 6. Z 字形变换【中等】

Z 字形变换

  • 将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。

  • 比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:

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

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

请你实现这个将字符串进行指定行数变换的函数:

  • string convert(string s, int numRows);

示例 1:

输入:s = “PAYPALISHIRING”, numRows = 3
输出:“PAHNAPLSIIGYIR”

示例 2:
输入:s = “PAYPALISHIRING”, numRows = 4
输出:“PINALSIGYAHRPI”
解释:
P I N
A L S I G
Y A H R
P I

解题思路

  • 1、通过观察Z字形排列的规律,可以发现每个字符在Z字形排列中的位置 与其在原字符串中的位置有一定的关系。
  • 2、 设 numRows 行字符串分别为 s1, s2, …… , sn,则:按顺序遍历字符串 s 时,每个字符 c 在 N 字形中对应的 行索引 先从 s1 增大至 sn,再从 sn 减小至 s1…… 如此反复
  • 3、 拼接 numRows每一行 字符串返回。

图解如下:

1、先把LEE按顺序放入res[0],res[1],res[2]
在这里插入图片描述
2、再把T按顺序放入res[1]
在这里插入图片描述

3、再把COD按顺序放入res[0],res[1],res[2],如果还有字符,如此反复即可在这里插入图片描述

Java实现

public class ZigzagConversion {
    public String convert(String s, int numRows) {
        if (numRows == 1) {
            return s;
        }

        StringBuilder[] rows = new StringBuilder[numRows];
        for (int i = 0; i < numRows; i++) {
            rows[i] = new StringBuilder();
        }

        int direction = 1; // 控制方向,1 表示向下,-1 表示向上
        int row = 0;
        for (char ch : s.toCharArray()) {
            rows[row].append(ch);
            if (row == 0) {//判断是否到第一行,到了就向下(可能是从下面遍历上来的)
                direction = 1;
            } else if (row == numRows - 1) {//判断是否到最后一行,到了就向上
                direction = -1;
            }
            row += direction;
        }

        StringBuilder result = new StringBuilder();
        for (StringBuilder sb : rows) {
            result.append(sb);
        }

        return result.toString();
    }

    public static void main(String[] args) {
        ZigzagConversion zigzagConversion = new ZigzagConversion();

        // Test Case 1
        String s1 = "PAYPALISHIRING";
        int numRows1 = 3;
        System.out.println("Test Case 1:");
        System.out.println("s: \"" + s1 + "\", numRows: " + numRows1);
        System.out.println("Result: \"" + zigzagConversion.convert(s1, numRows1) + "\""); // Expected: "PAHNAPLSIIGYIR"

        // Test Case 2
        String s2 = "PAYPALISHIRING";
        int numRows2 = 4;
        System.out.println("\nTest Case 2:");
        System.out.println("s: \"" + s2 + "\", numRows: " + numRows2);
        System.out.println("Result: \"" + zigzagConversion.convert(s2, numRows2) + "\""); // Expected: "PINALSIGYAHRPI"
    }
}

时间空间复杂度

  • 时间复杂度: O(n),需要遍历原字符串,其中 n 是字符串的长度。
  • 空间复杂度: O(n),需要存储整个字符串字符。
  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值