LeetCode 6. ZigZag Conversion(Python)兼翻译

本文介绍了一种字符串转换算法,即将字符串以锯齿形排列并按行读取。通过分析锯齿形排列的规律,提供了Python实现代码,用于解决LeetCode上的ZigZag Conversion问题。

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

6. ZigZag Conversion

转化成锯齿形

本题来自LeetCode OJ


题目翻译

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)
给定行数,将字符串"PAYPALISHIRING" 写成锯齿的形式,如下图所示:

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

And then read line by line: "PAHNAPLSIIGYIR"
然后一行一行的读取则为:
"PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:
所需输入的代码需要输入一个字符串和给定的行数:

string convert(string text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

注:ZigZag是锯齿形,也就是每条边是相同的字符个数


题目分析

根据锯齿状的结构,我们以字符串长度为10,ZZ n行为例:
第一行:第一个下标索引为0,下一个为竖下来这笔需要n-1个,斜过去这笔为n-1,所以第二个下标索引为2(n-1).我们很简单就可以看出规律,是(n-1)的倍数。
所以第二行呢?
第二行的情况一共有两种:
- 竖下来的第一行的下一个
- 斜上去第一行的上一个
也就是说是(n-1)整除余1或者余(n-2)
……
所以规律出来了:

if (i % nextnum) == j or (i % nextnum) == nextnum-j:
                        ZigZag += s[i]
                        dellist.append(i)

但是一个i在某一行就必定不在别的行,所以接下来我们进行删除操作,这样越到后面代码所需要迭代的次数就越少了。


代码示例

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if len(s) <= numRows or numRows == 1:
            ZigZag = s
        else:
            ZigZag = ""
            Candidate = [i for i in range(len(s))]
            nextnum = 2*(numRows-1)
            for j in range(numRows):
                dellist = []
                for i in Candidate:
                    if (i % nextnum) == j or (i % nextnum) == nextnum-j:
                        ZigZag += s[i]
                        dellist.append(i)
                for i in dellist:
                    Candidate.remove(i)
        return ZigZag

自己心累

最开始写的时候用错了remove,倒是程序总是得不到我想要的答案。不能够直接remove,我猜应该是remove了之后,for i in Candidate中的索引就变了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值