Leetcode 6. ZigZag Conversion

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)

Example 1:
Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”

Example 2:
Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:
P------I-------N
A—L-S—I–G
Y–A--H-R
P------I

代码部分

class Solution:
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows == 1:
            return s
        
        zig = [""] * numRows
        loc = self.location(numRows-1)
        #生成位置信息loc以便于后期list排单词的时候归位
        for c, l in zip(s,loc):
            zig[l] += c
        #c即从s中一个单词一个单词的选择
        #l用于控制每次用于放在list(zig)的哪个位置即从属于第几行的单词
        return "".join(zig)
    
    def location(self, bound):
        index, inc = 0, 1
        while True:
            yield index;
            #yield每次迭代输出next值,节省空间且避免反复调用
            #本代码最大的亮点设计
            if index == bound:
                inc = -1
            elif index == 0:
                inc = 1
            index = index + inc

Runtime: 76 ms, faster than 95.46% of Python3 online submissions for ZigZag Conversion.

Memory Usage: 12.5 MB, less than 88.94% of Python3 online submissions for ZigZag Conversion.

关于yield的用法可参考此篇文章,讲的非常简单易懂
https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/

主要思路:
以三行的z字型举例,现有一个S[‘abcdefghijk’]字符串,所以最后会以行为单位生成三个单词且最后单词拼接成为最后的输出;
第一个单词:a------e-------i
第二个单词:b–d—f---h—j
第三个单词:c------g-------k
很简单的看来就是s的单词依次出一个,光标指向从1行到2行到3行再到2行到1行重复循环往次(从这个角度考虑的话实现思路非常明确)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值