Leetcode(6)Z字形变换

Leetcode(6)Z字形变换

[题目表述]:

将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:

L C I R
E T O E S I I G
E D H N

之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。

第一次:找下标规律按行输出

执行用时:84 ms; 内存消耗:11.8MB 效果:还行

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        res=""
        List=[]
        #一组是2*numRows-2个
        #len(s)<numRows
        s_number,Aqueue=len(s),2*numRows-2
        if len(s)==0 or Aqueue==0:
            return s
        queue_number=s_number/Aqueue
        Yushu=s_number-queue_number*Aqueue
        for i in range(1,numRows+1):
            List.append("")
            for j in range(0,queue_number):
                if i==1 or i==numRows:
                    List[i-1]+=s[i+Aqueue*j-1]
                else:
                    List[i-1]+=s[i+Aqueue*j-1]
                    List[i-1]+=s[i+Aqueue*j-1+(numRows-i)*2]
            if Yushu>=i:
                List[i-1]+=s[i-1+s_number-Yushu]
                if (i+(numRows-i)*2)<=Yushu and i!=numRows:
                    List[i-1]+=s[i-1+s_number-Yushu+(numRows-i)*2]
            res+=List[i-1]
        return res

学习

  • 找规律,利用字符串列表存储每一行的输出字符

第二种方法:真·Z字字符串按行输出

执行用时:80 ms; 内存消耗:13.2MB 效果:非常好

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        L = ['' for x in range(numRows)]
        n = 0
        flag = True
        for i in s:
            if n > numRows - 2:
                flag = False
            elif n <= 0:
                flag = True
            L[n] += i
            if flag:
                n += 1
            else:
                n -= 1
        return ''.join(L)

学习

  • 按Z字走,n作为组数以及游标,flag作为标记表示目前是正走还是反走

  • 思路比我要好

  • ['' for x in range(numRows)] ''.join(L)

猜你喜欢

转载自www.cnblogs.com/ymjun/p/11681706.html