6. ZigZag Conversion [easy] (Python)

本文介绍了LeetCode上的ZigZag Conversion问题,解释了如何将字符串按ZigZag模式转换,并提供了两种Python解决方案:模拟过程和数学分析。通过示例展示了如何将'PAYPALISHIRING'转换为'PAHNAPLSIIGYIR'。

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

题目链接

https://leetcode.com/problems/zigzag-conversion/

题目原文

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 text, int nRows);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.

题目翻译

zigzag字符串转换,具体的规则见题目原文,太长不翻译了。。。
要写的函数接收两个参数,要转换的字符串text和zigzag的行数nRows,返回转换后的字符串。

思路方法

思路一

模拟书写zigzag字符串的过程。定义一个有numRows个元素的数组,每个元素初始是空字符串,代表numRows个行字符串的初始情况;然后扫描输入字符串s,依次将每个字符添加到相应行字符串的末尾;最后将所有行字符串拼接即得结果。
注意,代码中用了取模操作来判断:是否到了需要换一个方向书写zigzag字符的时候。

代码

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows <= 1 or numRows >= len(s):
            return s
        arr = [''] * numRows
        line, step = 0, -1
        for c in s:
            arr[line] += c
            if line % (numRows-1) == 0:
                step = - step
            line += step
        return ''.join(arr)

思路二

如果稍微考虑的数学一点,那么s中的第i个字符(下标从第0个开始),如果按照zigzag书写方式会出现在的行数为(行数为0到numRows-1行):
i % (2 * numRows - 2), if i % (2 * numRows - 2) < numRows
2 * numRows - 2 - (i % (2 * numRows - 2)), if i % (2 * numRows - 2) >= numRows
有了这个结果,对于任意一个位置的字符我们都知道它应该在第几行。下面的代码仍然是顺序扫描原字符串s,当然也可以有别的办法。

代码

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows <= 1 or numRows >= len(s):
            return s
        arr = [''] * numRows
        for i in xrange(len(s)):
            tmp = i % (numRows + numRows - 2)
            if tmp < numRows:
                arr[tmp] += s[i]
            else:
                arr[numRows + numRows - 2 - tmp] += s[i]
        return ''.join(arr)

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/52039689

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值