Leetcode(6)Z字形變換

Leetcode(6)Z字形變換

[題目表述]:

將一個給定字符串根據給定的行數,以從上往下、從左到右進行 Z 字形排列。
好比輸入字符串爲 "LEETCODEISHIRING" 行數爲 3 時,排列以下:app

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

以後,你的輸出須要從左往右逐行讀取,產生出一個新的字符串,好比:"LCIRETOESIIGEDHN"。學習

第一次:找下標規律按行輸出

執行用時:84 ms; 內存消耗:11.8MB 效果:還行code

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做爲標記表示目前是正走仍是反走leetcode

  • 思路比我要好字符串

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

相關文章
相關標籤/搜索