将字符串 "PAYPALISHIRING"
以 Z 字形排列成给定的行数:
P A H N A P L S I I G Y I R
之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR"
实现一个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入: s = "PAYPALISHIRING", numRows = 3 输出: "PAHNAPLSIIGYIR"
示例 2:
输入: 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
结果是:
[[‘P‘, ‘A‘, ‘Y‘, ‘P‘], [‘‘, ‘‘, ‘A‘, ‘‘], [‘‘, ‘L‘, ‘‘, ‘‘], [‘I‘, ‘S‘, ‘H‘, ‘I‘], [‘‘, ‘‘, ‘R‘, ‘‘], [‘‘, ‘I‘, ‘‘, ‘‘], [‘N‘, ‘G‘, ‘‘, ‘‘]] PINALSIGYAHRPI
当然对是没问题的,就是效率比较低。
这道题有个技巧就是不需要管空格,因为他是按行打印的,P I N,无论你中间隔多少,都是这几个字母,然后再搞清楚他的排列方式,一会向下一会向上的。
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
结果是:
[[‘P‘, ‘I‘, ‘N‘], [‘A‘, ‘L‘, ‘S‘, ‘I‘, ‘G‘], [‘Y‘, ‘A‘, ‘H‘, ‘R‘], [‘P‘, ‘I‘]] PINALSIGYAHRPI
原文地址:https://www.cnblogs.com/dahu-daqing/p/9307929.html
时间: 2024-11-09 10:07:30