LeetCode6字形变换

本文介绍了一种将字符串以Z字形排列并按行读取的算法实现,提供了两种方法的具体代码示例,适用于不同行数的字符串转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数:

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
"""方法一"""
class Solution:
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if 1 == numRows:
            return s

        len_s = len(s)
        piece_len = 2 * (numRows - 1)

        result = ""
        index = 0
        while index < len_s:
            result += s[index]
            index += piece_len
        for m in range(1, numRows - 1):
            index = m
            while index < len_s:
                result += s[index]
                right_index = index + (numRows - m - 1) * 2
                if right_index < len_s:
                    result += s[right_index]
                index += piece_len
        index = numRows - 1
        while index < len_s:
            result += s[index]
            index += piece_len

        return result


"""方法二"""


class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        # 若行数为1,直接输出即可
        if numRows == 1:
            return s

        # resultlist为结果的列表形式
        resultlist = []
        gap = 2 * numRows - 2

        # 用嵌套循环完成计算
        for i in range(0, numRows):
            temp1 = i
            temp2 = gap - i

            # 分两种情况,情况1:第0行和第numRows行。temp1为主列的循环
            if temp1 == 0 or temp1 == numRows - 1:
                while temp1 < len(s):
                    resultlist.append(s[temp1])
                    temp1 = temp1 + gap

            # 情况二:除首尾行外的其他行。temp1为主列的循环,temp2为插入元素的循环
            else:
                while temp1 < len(s):
                    resultlist.append(s[temp1])
                    temp1 = temp1 + gap
                    if temp2 < len(s):
                        resultlist.append(s[temp2])
                        temp2 = temp2 + gap

        # resultst为未最终返回结果字符串结果
        resultstr = ''.join(resultlist)
        return resultstr

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值