LeetCode ZigZag Conversion

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)


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 onvert(string text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".


这道题我自己做的时候~超时T^T,使用的是最简单的思维,对原始字符串中的字符进行遍历,分别分为我所建立的对应每一行数据的list中,最后对多个list进行整理合并。

附上代码:

nRows = 3
str_test = 'PAYPALISHIRING' 
str_matrix = [[] for i in range(nRows)]
str_list = list(str_test)

count = 0

while len(str_list)!=0:
    if count%(nRows-1) == 0:
        for i in range(nRows):
            if len(str_list)==0:
                break
            str_matrix[i].append(str_list.pop(0))
        count = count + 1
    else:
        for i in range(nRows):
            if len(str_list)==0:
                break
            if i == count%(nRows-1):
                str_matrix[i].append(str_list.pop(0))
            else:
                str_matrix[i].append('')
        count = count + 1
    
new_str = str()
#list->str
for i in range(nRows):
    temp_str = ''.join(str_matrix[i])
    new_str = new_str+temp_str

复杂度我认为是o(n^2),我猜测超时的原因,可能是我这里遍历了所有元素,每个元素都进行了判断和操作,浪费了很多时间。

后来我在网上看到了这个方法

主要依据ZigZag中元素间内在的数学关系。

附上我的代码:

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows == 1:
            return s
        
        str_test = s
        str_list = list(str_test)

        interval = 2*numRows - 2
        new_str = str()

        i = 0;
        while ((i<len(str_list)) and (i<numRows)) :
            index = i
            new_str= new_str + str_list[index]
    
            k=1 #k~even or odd
            while (index<len(str_list)):
                if (i==0 or i==(numRows - 1)):
                    index += 2*numRows-2
                else:
                    if(k&0x1):
                        index += 2*(numRows - 1 - i)
                    else: #even
                        index += 2*i
        
                if (index<len(str_list)):
                    #new_str.append(str_list[index])
                    new_str = new_str+str_list[index]
        
                k = k+1
        
            i = i + 1

        return new_str


这样我们只需要依据数学公式遍历每一个(新)行(外部循环~nRows)上的所有元素,并添加到new_str中即可。

遍历完成的时候,操作也就完成了。

这个方法的复杂度也是o(n^2),但是没有超时。我认为可能是一个是里外的循环换了一下,而且这种方法中的list操作少了很多,都是直接将元素加到new_str中。


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值