记录eetcode 6.Z 字形变换 两种解法

题目本身难度不大,但也耗费了很长时间。是因为受之前题目的影响,不采取最简单的方法,总是想要用一些所谓的便捷方法。

解法1:

class Solution(object):           
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        
        if len(s) <= numRows or numRows==1:
            return s 
        import numpy
        mask = numpy.zeros((numRows,numRows-1),numpy.int8)
        mask[0:numRows,0] = 1
        mask[range(1,numRows-1),range(numRows-2,0,-1)] = 1
        index = mask.T.flatten()
        
        n = len(s)/sum(index) if len(s)%sum(index)==0 else len(s)/sum(index)+1
        length = n*len(index)
        
        res = numpy.array(['']*length)
        index_n = numpy.array(index.tolist()*n)==numpy.array(1)
        s = list(s) + ['']*(sum(index_n)-len(s))
        
        res[index_n] = numpy.array(s)
        res = res.reshape((-1,numRows)).T.flatten().tolist()
        return ''.join(res) 

思路大致如下:

  1. 写出1和0构成的Z字形矩阵。转置并拉成一行。即获得index
  2. 将index中为1的位置,填入字段S中的字符
  3. 将结果返回为矩阵,再转置,再拉成一行。

这种方法遇到了运行时间过长的问题,总是报错,程序运行时间超过限制。

解法2:

这种算法是看了别人的思路后,发现就是简单的逻辑。直接计算每个字符应该在的位置,插到相应位置就行。

class Solution(object):           
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """   
        if numRows == 1 or len(s)<=numRows:
            return s
        res = ['' for i in range(numRows)]
        n = 2*numRows-2
        for i in range(len(s)):
            ch = s[i]
            i_n = i%n
            if i_n < numRows:
                res[i_n]+=ch
            else:
                i_n = i_n%numRows
                res[numRows-2-i_n]+=ch
        str_r = ''.join(res)
        return str_r

这种方法果然通过检测。。。。

果真是 能简单 就别复杂。。。。。

 

发布了45 篇原创文章 · 获赞 1 · 访问量 8572

猜你喜欢

转载自blog.csdn.net/qq_32110859/article/details/99700552