LeetCode ZigZag Conversion

来源:互联网 发布:网络贷款需要什么手续 编辑:程序博客网 时间:2024/06/05 19:45

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 = 3str_test = 'PAYPALISHIRING' str_matrix = [[] for i in range(nRows)]str_list = list(str_test)count = 0while 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->strfor 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
原创粉丝点击