6.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

示例 3:

输入:s = "A", numRows = 1
输出:"A"

提示:

  • 1 <= s.length <= 1000
  • s 由英文字母(小写和大写)、‘,’ 和 ‘.’ 组成
  • 1 <= numRows <= 1000

Python 实现

def convert(s: str, numRows: int) -> str:
    if numRows == 1 or numRows >= len(s):
        return s
    
    # 创建一个列表来存储每一行的字符
    rows = [''] * min(numRows, len(s))
    current_row = 0
    going_down = False
    
    for char in s:
        rows[current_row] += char
        # 当在第一行或最后一行时,改变方向
        if current_row == 0 or current_row == numRows - 1:
            going_down = not going_down
        current_row += 1 if going_down else -1
    
    # 将所有行的字符连接起来
    return ''.join(rows)

# 示例测试
print(convert("PAYPALISHIRING", 3))  # 输出: "PAHNAPLSIIGYIR"
print(convert("PAYPALISHIRING", 4))  # 输出: "PINALSIGYAHRPI"
print(convert("A", 1))               # 输出: "A"

Java 实现

public class Solution {
    public String convert(String s, int numRows) {
        if (numRows == 1 || numRows >= s.length()) {
            return s;
        }
        
        StringBuilder[] rows = new StringBuilder[Math.min(numRows, s.length())];
        for (int i = 0; i < rows.length; i++) {
            rows[i] = new StringBuilder();
        }
        
        int currentRow = 0;
        boolean goingDown = false;
        
        for (char c : s.toCharArray()) {
            rows[currentRow].append(c);
            if (currentRow == 0 || currentRow == numRows - 1) {
                goingDown = !goingDown;
            }
            currentRow += goingDown ? 1 : -1;
        }
        
        StringBuilder result = new StringBuilder();
        for (StringBuilder row : rows) {
            result.append(row);
        }
        
        return result.toString();
    }

    // 示例测试
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.convert("PAYPALISHIRING", 3));  // 输出: "PAHNAPLSIIGYIR"
        System.out.println(solution.convert("PAYPALISHIRING", 4));  // 输出: "PINALSIGYAHRPI"
        System.out.println(solution.convert("A", 1));               // 输出: "A"
    }
}

C++ 实现

#include <vector>
#include <string>
using namespace std;

class Solution {
public:
    string convert(string s, int numRows) {
        if (numRows == 1 || numRows >= s.length()) {
            return s;
        }
        
        vector<string> rows(min(numRows, int(s.length())));
        int currentRow = 0;
        bool goingDown = false;
        
        for (char c : s) {
            rows[currentRow] += c;
            if (currentRow == 0 || currentRow == numRows - 1) {
                goingDown = !goingDown;
            }
            currentRow += goingDown ? 1 : -1;
        }
        
        string result;
        for (string row : rows) {
            result += row;
        }
        
        return result;
    }
};

// 示例测试
int main() {
    Solution solution;
    cout << solution.convert("PAYPALISHIRING", 3) << endl;  // 输出: "PAHNAPLSIIGYIR"
    cout << solution.convert("PAYPALISHIRING", 4) << endl;  // 输出: "PINALSIGYAHRPI"
    cout << solution.convert("A", 1) << endl;               // 输出: "A"
    return 0;
}

代码解释

  1. 边界条件处理:如果 numRows 为 1 或者大于等于字符串的长度,直接返回原字符串。
  2. 初始化:创建一个列表(Python)或数组(Java/C++)来存储每一行的字符。
  3. 遍历字符串:根据当前行和方向(向下或向上)将字符添加到对应的行中。
  4. 方向切换:当到达第一行或最后一行时,切换方向。
  5. 结果拼接:将所有行的字符按顺序拼接成最终的结果字符串。

复杂度分析

  • 时间复杂度:O(n),其中 n 是字符串的长度。我们只需要遍历一次字符串。
  • 空间复杂度:O(n),用于存储每一行的字符。

这些代码在给定的约束条件下都能高效运行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

早退的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值