將字符串 "PAYPALISHIRING"
以 Z 字形排列成給定的行數:app
P A H N A P L S I I G Y I R
以後從左往右,逐行讀取字符:"PAHNAPLSIIGYIR"
函數
實現一個將字符串進行指定行數變換的函數:spa
string convert(string s, int numRows);
示例 1:code
輸入: s = "PAYPALISHIRING", numRows = 3 輸出: "PAHNAPLSIIGYIR"
示例 2:blog
輸入: s = "PAYPALISHIRING", numRows = 4 輸出: "PINALSIGYAHRPI" 解釋: P I N A L S I G Y A H R P I
leetcode上的一道題,一開始看到這個題目,很耿直的就直接作了: 很好的對應劉每個空格。。
def convert(s,num): chushu=num*2-2 base=1+num-2 if chushu==0: return s yushu=len(s)%chushu if yushu==0: lieshu = len(s) / chushu * base elif yushu<=num: lieshu=len(s)/chushu*base+1 elif yushu> num: lieshu = len(s) / chushu * base + yushu-num+1 newdata=[['' for j in range(num)] for i in range(lieshu)] k=0 for i in range(lieshu): for j in range(num): if k<len(s): if i%(num-1)==0 or (i+j)%(num-1)==0: newdata[i][j]=s[k] k+=1 # print newdata a=[] for j in range(num): a.extend([i[j] for i in newdata if i[j]!='']) return ''.join(a) if __name__ == '__main__': s='PAYPALISHIRING' res= convert(s,4) print res
結果是:leetcode
[['P', 'A', 'Y', 'P'], ['', '', 'A', ''], ['', 'L', '', ''], ['I', 'S', 'H', 'I'], ['', '', 'R', ''], ['', 'I', '', ''], ['N', 'G', '', '']] PINALSIGYAHRPI
固然對是沒問題的,就是效率比較低。字符串
這道題有個技巧就是不須要管空格,由於他是按行打印的,P I N,不管你中間隔多少,都是這幾個字母,而後再搞清楚他的排列方式,一會向下一會向上的。string
def convert3(s,num): chushu = num * 2 - 2 base = 1 + num - 2 if chushu == 0: return s newdata=[[] for i in range(num)] c=0 direc=1 #方向 for i in s: newdata[c].append(i) if c>=num-1: direc=-1 elif direc==-1 and c==0: direc=1 c+=direc print newdata return ''.join([''.join(i) for i in newdata]) if __name__ == '__main__': s='PAYPALISHIRING' res= convert3(s,4) print res
結果是:class
[['P', 'I', 'N'], ['A', 'L', 'S', 'I', 'G'], ['Y', 'A', 'H', 'R'], ['P', 'I']] PINALSIGYAHRPI