【LeetCode】6. ZigZag Conversion(Python)

本文介绍了一种将字符串以Z字形图案写入多行并逐行读取的算法实现,通过Python代码示例详细解释了如何根据给定的行数对字符串PAYPALISHIRING进行转换。

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

Problem

字符串"PAYPALISHIRING"在给定行数上以Z字形图案写入,如下所示:(您可能希望以固定字体显示此图案以获得更好的易读性)
在这里插入图片描述
然后逐行阅读: “PAHNAPLSIIGYIR”

编写将采用字符串的代码并在给定多行的情况下进行此转换:
string convert(string s,int numRows);

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

例2:
输入: s =“PAYPALISHIRING”,numRows = 4
输出: “PINALSIGYAHRPI”
说明:
leetCode-p-2

Algorithmic thinking

再如numRows是5,我们看到这样的锯齿形图案:

images-leetcode-6-at
我们可以看到数字0~7在这里是一个小模式,如果我们除以8,我们可以在其他小模式中获得相同的数字。如
0%8 = 0; 8%8 = 0
1%8 = 1; 9%8 = 1
所以我们可以使用此功能并将它们过滤到我们存储的行中。


Python solution

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
字符串"PAYPALISHIRING"在给定行数上以Z字形图案写入,然后逐行阅读: "PAHNAPLSIIGYIR"
编写将采用字符串的代码并在给定多行的情况下进行此转换:
string convert(string s,int numRows);

----

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
(you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
"""


class Solution(object):
    def convert(self, s, numRows):
        """
        再如numRows是5,我们看到这样的锯齿形图案:(here Algorithmic thinking)
        
        我们可以看到数字0~7在这里是一个小模式,如果我们除以8,我们可以在其他小模式中获得相同的数字。如
        0%8 = 0; 8%8 = 0 
        1%8 = 1; 9%8 = 1 
        所以我们可以使用此功能并将它们过滤到我们存储的行中。
        
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows == 1:
            return s
        rows = [''] * numRows
        num = (numRows-1) * 2
        for i, item in enumerate(s):
            if i % num >= numRows:
                rows[(num - i % num)] += item
            else:
                rows[i % num] += item
        return ''.join(rows)


if __name__ == '__main__':
    string = 'my path'
    result = Solution().convert(string, 2)
    print(result)


Related documents

https://leetcode.com/problems/zigzag-conversion/discuss/3736/My-easy-read-python-solution

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值