Leetcode-Medium 6. ZigZag Conversion

简介: Leetcode-Medium 6. ZigZag Conversion

题目描述


字符串“PAYPALISHIRING”以Z字形图案写在给定数量的行上,如下所示:(您可能希望以固定字体显示此图案以获得更好的易读性):


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


然后返回: "PAHNAPLSIIGYIR"


思路


先声明一个长度为numRows的列表,然后遍历原有字符串:

当当前索引:index==0时,step=1,如果当前索引index==numRows时,相当于控制遍历的上下方向。


代码实现



class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if numRows==1 or len(s)<=numRows:
            return s
        ans=['']*numRows
        index,step=0,1
        for x in s:
            ans[index]+=x
            if index==0:
                step=1
            elif index==numRows-1:
                step=-1
            index+=step
        return "".join(ans)


同时安利大家一个代码执行模拟的网站:http://www.pythontutor.com/live.html#mode=edit



74.png

相关文章
|
6月前
Leetcode 6.ZigZag Conversion
如上所示,这就是26个小写字母表的5行曲折变换。 其中在做这道题的时候把不需要我们构造出这样五行字符,然后拼接。其实你把字母换成1-n的数字,很容易找到每个位置的字母在原字符串中的位置。
23 0
LeetCode---Problem6 ZigZag Conversion
ZigZag问题思路。代码整洁并不一定执行速度就好~
762 0
|
机器学习/深度学习 Perl
|
Perl
[LeetCode]--6. 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
1177 0
LeetCode - 6. ZigZag Conversion
6. ZigZag Conversion  Problem's Link  ---------------------------------------------------------------------------- Mean:  给你一个字符串,让你将其按照倒‘之’字型排列,然后输出排列后的顺序.
879 0
|
索引 Java Perl
LeetCode 6 ZigZag Conversion(Z型转换)(String)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/48634663 ...
784 0
|
C++
[LeetCode] Zigzag Conversion
The key challenge to this problem is to make the code clean. This post has shared a nice example, which is rewritten below in C++.
881 0
|
Python Go Perl
leetcode 6 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 ...
822 0

热门文章

最新文章