Z字形变换
将字符串"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"
def convert(self, s, numRows):
d =list(s)
lenght =len(s)
if numRows==1:
return s
su1 =2*(numRows-1)
count1 = lenght//su1
duoyu = lenght-count1*su1
if duoyu ==0:
for iin range(lenght):
if i % su1 ==0:
d[i // su1] = s[i]
elif (i-numRows+1) % (su1) ==0:
wh = i // (su1)
d[(numRows-2)*count1*2+count1+wh] = s[i]
else:
if i%(su1)
zh=0
if i//(su1)>0:
zh = i//(su1)*2
index = ((i % (su1)-1)*2*count1+count1)+zh
d[index] = s[i]
else:
zh=1
if i//(su1)>0:
zh = i//(su1)*2+1
index = ((su1 - i%(su1)-1 )*2 * count1 + count1) + zh
d[index] = s[i]
return ''.join(d)
elif duoyu >0 and duoyu<=numRows:
for iin range(lenght):
if i % su1 ==0:
d[i // su1] = s[i]
elif (i-numRows+1) % (su1) ==0:
if duoyu > i % (su1) % numRows:
do = i % (su1) % numRows
else:
do = duoyu
wh = i // (su1)
d[(numRows-2)*count1*2+count1+do+wh] = s[i]
else:
if i%(su1)
if duoyu > i%(su1)%numRows:
do = i%(su1)%numRows
else:
do = duoyu
zh=0
if i//(su1)>0:
zh = i//(su1)*2
index = ((i % (su1)-1)*2*count1+count1)+zh+do
d[index] = s[i]
else:
if duoyu > (su1 - i%(su1))%numRows:
do = (su1 - i%(su1))%numRows
else:
do = duoyu
zh=1
if i//(su1)>0:
zh = i//(su1)*2+1
index = ((su1 - i%(su1)-1 )*2 * count1 + count1) + zh + do
d[index] = s[i]
return ''.join(d)
else:# duoyu>numRows
for iin range(lenght):
if i % su1 ==0:
d[i // su1] = s[i]
elif (i-numRows+1) % (su1) ==0:
do = duoyu-1
wh = i // (su1)
d[(numRows-2)*count1*2+count1+do+wh] = s[i]
else:
if i%(su1)
gh = numRows - duoyu % numRows-1
if i % (su1) <= gh:
do = i % (su1) % numRows
else:
do = (i % (su1) % numRows - gh) *2 + gh
zh=0
if i//(su1)>0:
zh = i//(su1)*2
index = ((i % (su1)-1)*2*count1+count1)+zh+do
d[index] = s[i]
else:
if duoyu >= (su1 - i%(su1))%(numRows-1):
gh = numRows - duoyu % (numRows-1)
if (su1 - i % (su1)) % numRows <= gh:
do = (su1 - i%(su1)) % numRows
else:
if i>su1*count1:
do = ((su1 - i % (su1)) % numRows - gh) *2 + gh
else:
do = ((su1 - i%(su1)) % numRows - gh) *2 + gh
else:
do = duoyu
zh=1
if i//(su1)>0:
zh = i//(su1)*2+1
index = ((su1 - i%(su1)-1 )*2 * count1 + count1) + zh + do
d[index] = s[i]
return ''.join(d)