将给定字符串按照锯齿形状转换!
由于最后的规则写得太渣所以运行很慢!先贴出来再优化!
class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ result = '' strlen = len(s) if numRows == 1 or strlen == 0: return s elif numRows == 2: list1 = [] list2 = [] i = 0 while i < strlen: list1.append(s[i]) i += 1 if i >= strlen: break list2.append(s[i]) i += 1 print list1 print list2 list1 = list1 + list2 return result.join(list1) rows = (strlen / (numRows+1))*2 if strlen % (numRows+1) != 0 : rows = rows + 2 currentRow = 0 print rows i = 0 d = dict() col = 0 while currentRow < rows: col = 0 dict2 = dict() if currentRow%2==0: while col < numRows: if i < strlen: dict2[col] = s[i] else: dict2[col] = '' i += 1 col += 1 else: maxi = i+numRows - 2 curi = maxi - 1 dict2[0] = '' col = 1 while i < maxi: if curi < strlen: dict2[col] = s[curi] else: dict2[col] = '' i += 1 curi -= 1 col += 1 dict2[numRows-1] = '' d[currentRow] = dict2 currentRow += 1 i = 0 while i < numRows: rowi = 0 while rowi < rows: result += d[rowi][i] rowi += 1 i += 1 return result
QAQ 弱成狗
Leave a Comment