将一个给定字符串根据给定的行数,以从上往下、从左到右进行 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
执行用时: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