Leetcode6-ZigZag Conversion(Python3)

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

My Solution

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows == 1:
            return s
        r, dict_s = '', {}
        for i in range(len(s)):
            row = i % (numRows + numRows - 2)
            if row >= numRows:
                row = numRows + numRows - 2 - row
            if row in dict_s.keys():
                dict_s[row] = dict_s[row] + s[i]
            else:
                dict_s[row] = s[i]
        for i in range(max(dict_s.keys())+1):
            r = r + dict_s[i]
        return r

Reference (转)

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

        L = [''] * numRows
        index, step = 0, 1

        for x in s:
            L[index] += x
            if index == 0:
                step = 1
            elif index == numRows -1:
                step = -1
            index += step

        return ''.join(L)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,776评论 0 33
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • 简书第一天,其实我也没有想好写些什么。 昨天这个时候,我还在想,想了很多东西,想的很绝望,这种状态已经跟着我很久了...
    b608cc6fc24a阅读 153评论 0 0
  • 果真需要好好的先熟悉彩铅的脾性,不然就会手残党的我一样。第一幅勾线有些画残了~ 经过看视频,反复练习后,第二幅勾线...
    翾萱宝宝阅读 112评论 2 5
  • 很多努力,如果方向的对的,最终会得到补偿。 一路走来,从小学到高中,再到现在的大学,留下的足迹,都已经慢慢远去,都...
    董欧阅读 842评论 2 2