【LEETCODE】6-ZigZag Conversion

本文介绍了一种将字符串按照Zigzag模式重新排列的方法,包括核心思路、数学规律总结及实现代码,适用于多行输出场景。

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

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


题意:

给一个字符串和一个数字n

将此字符串按着 Zigzag即循环对角线结构 的方式重拍成n行

将重拍后的字符按着横向读取,返回新的字符串


Zigzag即循环对角线结构



参考

http://www.cnblogs.com/zuoyuan/p/3777745.html?utm_source=tuicool


思路:

    


没有想到建数组,没想到拼接,而要一次性读出来
需要用数学的方式把角标的规律总结出来
需要遍历nRow次,找到符合条件的角标
除去端点还有特殊情况,参差不齐
建一个字符串数组tmp,长度为nRow
tmp的每个元素内用来记录相应行的字符
然后将tmp的nRow个元素join在一起
就得到按行读取的新string

通过 index 去指向 tmp 的位置

通过 step 去控制 index 指向位置的规律

通过 i 去读 s 的元素


class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        
        if numRows==1:                                  #端点情况
            return s
        
        tmp=['' for i in range(numRows)]                #字符串数组
        
        index=-1                                        #通过 index 去指向 tmp 的位置
        step=1                                          #通过 step 去控制 index 指向位置的规律
        
        for i in range(len(s)):                         #通过 i 去读 s 的元素
            index+=step                                 #前走一步,直到numRows换行
            if index==numRows:                          
                index-=2                                #换行到达的位置
                step=-1                                 #换行后后走一步
            elif index==-1:                             #换到头后,变成tmp1,方向前走
                index=1
                step=1
            tmp[index]+=s[i]
        
        return ''.join(tmp)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值