LeetCode 6. ZigZag Conversion & 字符串
ZigZag Conversion
看了三遍题目才懂,都有点怀疑自己是不是够聪明...
就是排成这个样子啦,然后从左往右逐行读取返回。
这题看起来很简单,做起来,应该也很简单。
通过位置计算行数:
P I N
A L S I G
Y A H R
P I
0,0 1,1 2,2 3,3 4,2 5,1 6,0 (期望)
用简单的先思考:
P A H N
A P L S I I G
Y I R
0,0 1,1 2,2 3,3 4,0 %4 (3+1)可以解决正常的
3,1(期望) 特殊的3(2行2排的P,用1- (%4-row) )
这里(3+1)
以及1- (%4-row)
中的1
作为取余底数的延长
找某个键所在行数
# find k in line
def findLine(k,rows):
# 延长,去掉斜路两头
prolong=rows-2
# 取模底
modulo=rows+prolong
print(modulo,prolong+1,k%modulo,(k%modulo-rows+1)%(prolong+1),(k%modulo) if (k%modulo)<rows else prolong-(k%modulo-rows))
return (k%modulo) if (k%modulo)<rows else prolong-(k%modulo-rows+1)%(prolong+1)
第1次提交
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
zigzag=''
# each line add 'c' to zigzag string.
for n in range(numRows):
for k,c in enumerate(s):
#print(k,c,end=" ")
if findLine(k,numRows) == n:
zigzag=zigzag+c
return zigzag
# find k in line
def findLine(k,rows):
# 延长,去掉斜路两头
prolong=rows-2
# 取模底
modulo=rows+prolong
#print(modulo,prolong+1,k%modulo,(k%modulo-rows+1)%(prolong+1),(k%modulo) if (k%modulo)<rows else prolong-(k%modulo-rows))
return (k%modulo) if (k%modulo)<rows else prolong-(k%modulo-rows)
if __name__ == "__main__":
data = [
{
"input":{
's':'PAYPALISHIRING',
'numRows':4
},
"output":"PINALSIGYAHRPI",
},{
"input":{
's':'PAYPALISHIRING',
'numRows':3
},
"output":"PAHNAPLSIIGYIR",
},
];
for d in data:
print(d['input']['s'],d['input']['numRows'])
result=Solution().convert(d['input']['s'],d['input']['numRows'])
print(result)
if result==d['output']:
print("--- ok ---")
else:
print("--- error ---")
Runtime Error:
Runtime Error Message:
Line 27: ZeroDivisionError: integer division or modulo by zero
Last executed input:
"A"
1
粗心+1,findLine()
函数里没有检验值的有效性。
第2次提交
# find k in line
def findLine(k,rows):
# 延长,去掉斜路两头
prolong=rows-2
# 取模底
modulo=rows+prolong
# validity check
if prolong<0:
prolong=0
if modulo<=0:
modulo=1
#print(modulo,prolong+1,k%modulo,(k%modulo-rows+1)%(prolong+1),(k%modulo) if (k%modulo)<rows else prolong-(k%modulo-rows))
return (k%modulo) if (k%modulo)<rows else prolong-(k%modulo-rows)
Time Limit Exceeded:
"kvzeeubynglxfdedshtpobqsdhufkzgwuhaabdzrlkosnuxibrxssnkxuhcggkecshdvkcmymdqbxolbfjtzyfwtmbbungzfpcbbgpzusqxqejrlsmkqtglijpcxxbcmffnlvnfpddfjmyugkeyemkmyzqvwszkxfxlckqrpvzyjxupkyoonaclbsgzmhjmogxstpkilljwidoseeitemefhmgtvpfkxecquobhzkfkptetxpmdbskigqecflmdqqvmfwveiaqyuvrtkgxlyhwhyalfnzifpgrucoblprjloceykbkjlisjkdoxczdtfwqjlrwckhnzkrxuvjfgtzrdchdgiicneszrlvtxdiwncwjxhrfbqygvfjdorfdyzcrkylidvgqxebwmubplzxihjlvataasdsfdfngavyyabuowyfhzcpglcdoxeoqjivmnkuofsohtivpiayifpoquugryvjjfgvtqrjyjxhefdwqfwykmodiijzigjrmpohifqiqnpvuutkcpiodzrljdlslwlxnagxhwfylxvgtosvfdkjcdulihfudrtrtaoaywakvvqolkmtnycpdwdmeigjbbcubrxapxmkveaiombckftocwaifitgjwdnpapezbqwhqhvdizpotdspfcwpxfbtiqikfolieipxpmazmrphxjyenvulcxeknpwsfhckptjgflitczczjbeyyajaxqmkhiempgyfzhngsvcvxewghcgfcqhzitlpbpbrvaywjlfcjhzgnxoxauecmmeufpljfpacrazaneewndecbuzbrgffsjczznieckitkhwynawcgdfjzgmqmrygbaicpqiudqpnylnnoksupzdofphuifcjhknydvsgmivmvjbjttdksiyazhuimytvjhuocmuqwpcsyedtzjdsresrlozamsvxbrlegfucxzwxfcrelwyeaqvoewotrlssdeyjltnkumibozfzxe"
200
超时了,加一个时钟本地看看时间:
运行时间
PAYPALISHIRING 4
PINALSIGYAHRPI
--- ok --- -3.590000000000017e-05
PAYPALISHIRING 3
PAHNAPLSIIGYIR
--- ok --- -2.6699999999999294e-05
A 1
A
--- ok --- -8.399999999998686e-06
kvzeeubynglxfdedshtpobqsdhufkzgwuhaabdzrlkosnuxibrxssnkxuhcggkecshdvkcmymdqbxolbfjtzyfwtmbbungzfpcbbgpzusqxqejrlsmkqtglijpcxxbcmffnlvnfpddfjmyugkeyemkmyzqvwszkxfxlckqrpvzyjxupkyoonaclbsgzmhjmogxstpkilljwidoseeitemefhmgtvpfkxecquobhzkfkptetxpmdbskigqecflmdqqvmfwveiaqyuvrtkgxlyhwhyalfnzifpgrucoblprjloceykbkjlisjkdoxczdtfwqjlrwckhnzkrxuvjfgtzrdchdgiicneszrlvtxdiwncwjxhrfbqygvfjdorfdyzcrkylidvgqxebwmubplzxihjlvataasdsfdfngavyyabuowyfhzcpglcdoxeoqjivmnkuofsohtivpiayifpoquugryvjjfgvtqrjyjxhefdwqfwykmodiijzigjrmpohifqiqnpvuutkcpiodzrljdlslwlxnagxhwfylxvgtosvfdkjcdulihfudrtrtaoaywakvvqolkmtnycpdwdmeigjbbcubrxapxmkveaiombckftocwaifitgjwdnpapezbqwhqhvdizpotdspfcwpxfbtiqikfolieipxpmazmrphxjyenvulcxeknpwsfhckptjgflitczczjbeyyajaxqmkhiempgyfzhngsvcvxewghcgfcqhzitlpbpbrvaywjlfcjhzgnxoxauecmmeufpljfpacrazaneewndecbuzbrgffsjczznieckitkhwynawcgdfjzgmqmrygbaicpqiudqpnylnnoksupzdofphuifcjhknydvsgmivmvjbjttdksiyazhuimytvjhuocmuqwpcsyedtzjdsresrlozamsvxbrlegfucxzwxfcrelwyeaqvoewotrlssdeyjltnkumibozfzxe 200
kmavwupczbbfreepjaexllzuqzpabgxfnyviuendheegijmwlllmnxyvcdfkaeedrtucecaabdzaxusysozhddxbtfsnrprfggoodzfbdfhfqjnjssfgcjdvafchgvlzuyyjzfqywnkbayizfbaegruvcwhorkuxwbihjyptawfbkachphbnzlwdwctyzipinrdgzalxlhwktcqcovdcgslofdnrxgfuzecjxsohzieqggbnjwmrcieqxivxmsimvrsgncyndkvgkhusbxcogaudfnihrshcczozpgthfqggtyikfiguejvpdcvpmqsuiephxaindryhyvkiklkzfmncnpqnmhoxoykqakmcujsdwuauqrgypblryzxjyedoqvbolwjjfbfjzpftfchjdgzutzvcizcttfyxqicforljwdjfhtkygkmjjjnbsxtybihpdulekvnjfcsgkdhgzbwfmfkqsipyfwvcewpmbcynvbokkjglmebpjoxjzrdctupiltsliudqbjvkxoznsqcieieugyyjrjjargrxzlpmhhsfppumiorikzhmmqnizytffatglqmvlaipjiyqxhjhnpupwpiochvecxyuimxlulubxtoqcgkfwmkckpftpicfriqsnvoiyludtevyzbdnqrftfalxzpijpjdedwddvlcsfwsfrjflpemmwssyvldruqxtlgqnookdapzemgzaylximefhdsmcwvvkefhxmqyqbyglhrzixwlqkvqevsgbgwbtzfsdoeuzmspckpvaxxxfpzftdnwxekdxltjwfcpcjckkdgrqfuterklilpzifwvhhiyzbfaeyouwajudcqxqrovucttoperfekxtkwykacoofobtopamrnvyolatwiscgaaslmkedbhvvesfvkygeqmjzmoxlmelpthtkanjimxkmetruoenbmgsyuixoccbsdpbotidbzpwwjfkjdgzilmixlee
--- ok --- -0.07744500000000001
比其他的是慢了1000倍,0.77ms,目标:优化到1ms.
分析
问题就在于,外层的(计算层数的)for没必要循环的(随着层数增大,每一层都O(n),多少无用功),只要分numRows个列表,一个for就遍历完。
改完测一下时间
PAYPALISHIRING 4
PINALSIGYAHRPI
--- ok --- -2.4100000000000857e-05
PAYPALISHIRING 3
PAHNAPLSIIGYIR
--- ok --- -1.9699999999999232e-05
A 1
A
--- ok --- -1.1399999999999952e-05
kvzeeubynglxfdedshtpobqsdhufkzgwuhaabdzrlkosnuxibrxssnkxuhcggkecshdvkcmymdqbxolbfjtzyfwtmbbungzfpcbbgpzusqxqejrlsmkqtglijpcxxbcmffnlvnfpddfjmyugkeyemkmyzqvwszkxfxlckqrpvzyjxupkyoonaclbsgzmhjmogxstpkilljwidoseeitemefhmgtvpfkxecquobhzkfkptetxpmdbskigqecflmdqqvmfwveiaqyuvrtkgxlyhwhyalfnzifpgrucoblprjloceykbkjlisjkdoxczdtfwqjlrwckhnzkrxuvjfgtzrdchdgiicneszrlvtxdiwncwjxhrfbqygvfjdorfdyzcrkylidvgqxebwmubplzxihjlvataasdsfdfngavyyabuowyfhzcpglcdoxeoqjivmnkuofsohtivpiayifpoquugryvjjfgvtqrjyjxhefdwqfwykmodiijzigjrmpohifqiqnpvuutkcpiodzrljdlslwlxnagxhwfylxvgtosvfdkjcdulihfudrtrtaoaywakvvqolkmtnycpdwdmeigjbbcubrxapxmkveaiombckftocwaifitgjwdnpapezbqwhqhvdizpotdspfcwpxfbtiqikfolieipxpmazmrphxjyenvulcxeknpwsfhckptjgflitczczjbeyyajaxqmkhiempgyfzhngsvcvxewghcgfcqhzitlpbpbrvaywjlfcjhzgnxoxauecmmeufpljfpacrazaneewndecbuzbrgffsjczznieckitkhwynawcgdfjzgmqmrygbaicpqiudqpnylnnoksupzdofphuifcjhknydvsgmivmvjbjttdksiyazhuimytvjhuocmuqwpcsyedtzjdsresrlozamsvxbrlegfucxzwxfcrelwyeaqvoewotrlssdeyjltnkumibozfzxe 200
kmavwupczbbfreepjaexllzuqzpabgxfnyviuendheegijmwlllmnxyvcdfkaeedrtucecaabdzaxusysozhddxbtfsnrprfggoodzfbdfhfqjnjssfgcjdvafchgvlzuyyjzfqywnkbayizfbaegruvcwhorkuxwbihjyptawfbkachphbnzlwdwctyzipinrdgzalxlhwktcqcovdcgslofdnrxgfuzecjxsohzieqggbnjwmrcieqxivxmsimvrsgncyndkvgkhusbxcogaudfnihrshcczozpgthfqggtyikfiguejvpdcvpmqsuiephxaindryhyvkiklkzfmncnpqnmhoxoykqakmcujsdwuauqrgypblryzxjyedoqvbolwjjfbfjzpftfchjdgzutzvcizcttfyxqicforljwdjfhtkygkmjjjnbsxtybihpdulekvnjfcsgkdhgzbwfmfkqsipyfwvcewpmbcynvbokkjglmebpjoxjzrdctupiltsliudqbjvkxoznsqcieieugyyjrjjargrxzlpmhhsfppumiorikzhmmqnizytffatglqmvlaipjiyqxhjhnpupwpiochvecxyuimxlulubxtoqcgkfwmkckpftpicfriqsnvoiyludtevyzbdnqrftfalxzpijpjdedwddvlcsfwsfrjflpemmwssyvldruqxtlgqnookdapzemgzaylximefhdsmcwvvkefhxmqyqbyglhrzixwlqkvqevsgbgwbtzfsdoeuzmspckpvaxxxfpzftdnwxekdxltjwfcpcjckkdgrqfuterklilpzifwvhhiyzbfaeyouwajudcqxqrovucttoperfekxtkwykacoofobtopamrnvyolatwiscgaaslmkedbhvvesfvkygeqmjzmoxlmelpthtkanjimxkmetruoenbmgsyuixoccbsdpbotidbzpwwjfkjdgzilmixlee
--- ok --- -0.0005619000000000006
bingo! 0.56ms
提交看看,肯定AC
第3次提交 完整代码
import time
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
# create list array save each line
listStr=[]
for n in range(numRows):
try:
listStr[n]
except:
listStr.append('')
# each line add char to listStr[n].
for k,c in enumerate(s):
#print(k,c,end=" ")
n=findLine(k,numRows)
listStr[n]=listStr[n]+c
# joint str
zigzag=''.join(listStr)
return zigzag
# find k in line
def findLine(k,rows):
# 延长,去掉斜路两头
prolong=rows-2
# 取模底
modulo=rows+prolong
# validity check
if prolong<0:
prolong=0
if modulo<=0:
modulo=1
#print(modulo,prolong+1,k%modulo,(k%modulo-rows+1)%(prolong+1),(k%modulo) if (k%modulo)<rows else prolong-(k%modulo-rows))
x=k%modulo
return (x) if (x)<rows else prolong-(x-rows)
if __name__ == "__main__":
data = [
{
"input":{
's':'PAYPALISHIRING',
'numRows':4
},
"output":"PINALSIGYAHRPI",
},{
"input":{
's':'PAYPALISHIRING',
'numRows':3
},
"output":"PAHNAPLSIIGYIR",
},
{
"input":{
's':'A',
'numRows':1
},
"output":"A",
},
{
"input":{
's':'kvzeeubynglxfdedshtpobqsdhufkzgwuhaabdzrlkosnuxibrxssnkxuhcggkecshdvkcmymdqbxolbfjtzyfwtmbbungzfpcbbgpzusqxqejrlsmkqtglijpcxxbcmffnlvnfpddfjmyugkeyemkmyzqvwszkxfxlckqrpvzyjxupkyoonaclbsgzmhjmogxstpkilljwidoseeitemefhmgtvpfkxecquobhzkfkptetxpmdbskigqecflmdqqvmfwveiaqyuvrtkgxlyhwhyalfnzifpgrucoblprjloceykbkjlisjkdoxczdtfwqjlrwckhnzkrxuvjfgtzrdchdgiicneszrlvtxdiwncwjxhrfbqygvfjdorfdyzcrkylidvgqxebwmubplzxihjlvataasdsfdfngavyyabuowyfhzcpglcdoxeoqjivmnkuofsohtivpiayifpoquugryvjjfgvtqrjyjxhefdwqfwykmodiijzigjrmpohifqiqnpvuutkcpiodzrljdlslwlxnagxhwfylxvgtosvfdkjcdulihfudrtrtaoaywakvvqolkmtnycpdwdmeigjbbcubrxapxmkveaiombckftocwaifitgjwdnpapezbqwhqhvdizpotdspfcwpxfbtiqikfolieipxpmazmrphxjyenvulcxeknpwsfhckptjgflitczczjbeyyajaxqmkhiempgyfzhngsvcvxewghcgfcqhzitlpbpbrvaywjlfcjhzgnxoxauecmmeufpljfpacrazaneewndecbuzbrgffsjczznieckitkhwynawcgdfjzgmqmrygbaicpqiudqpnylnnoksupzdofphuifcjhknydvsgmivmvjbjttdksiyazhuimytvjhuocmuqwpcsyedtzjdsresrlozamsvxbrlegfucxzwxfcrelwyeaqvoewotrlssdeyjltnkumibozfzxe',
'numRows':200
},
"output":"kmavwupczbbfreepjaexllzuqzpabgxfnyviuendheegijmwlllmnxyvcdfkaeedrtucecaabdzaxusysozhddxbtfsnrprfggoodzfbdfhfqjnjssfgcjdvafchgvlzuyyjzfqywnkbayizfbaegruvcwhorkuxwbihjyptawfbkachphbnzlwdwctyzipinrdgzalxlhwktcqcovdcgslofdnrxgfuzecjxsohzieqggbnjwmrcieqxivxmsimvrsgncyndkvgkhusbxcogaudfnihrshcczozpgthfqggtyikfiguejvpdcvpmqsuiephxaindryhyvkiklkzfmncnpqnmhoxoykqakmcujsdwuauqrgypblryzxjyedoqvbolwjjfbfjzpftfchjdgzutzvcizcttfyxqicforljwdjfhtkygkmjjjnbsxtybihpdulekvnjfcsgkdhgzbwfmfkqsipyfwvcewpmbcynvbokkjglmebpjoxjzrdctupiltsliudqbjvkxoznsqcieieugyyjrjjargrxzlpmhhsfppumiorikzhmmqnizytffatglqmvlaipjiyqxhjhnpupwpiochvecxyuimxlulubxtoqcgkfwmkckpftpicfriqsnvoiyludtevyzbdnqrftfalxzpijpjdedwddvlcsfwsfrjflpemmwssyvldruqxtlgqnookdapzemgzaylximefhdsmcwvvkefhxmqyqbyglhrzixwlqkvqevsgbgwbtzfsdoeuzmspckpvaxxxfpzftdnwxekdxltjwfcpcjckkdgrqfuterklilpzifwvhhiyzbfaeyouwajudcqxqrovucttoperfekxtkwykacoofobtopamrnvyolatwiscgaaslmkedbhvvesfvkygeqmjzmoxlmelpthtkanjimxkmetruoenbmgsyuixoccbsdpbotidbzpwwjfkjdgzilmixlee",
},
];
for d in data:
print(d['input']['s'],d['input']['numRows'])
# 计算运行时间
start = time.perf_counter()
result=Solution().convert(d['input']['s'],d['input']['numRows'])
end = time.perf_counter()
print(result)
if result==d['output']:
print("--- ok ---",end="\t")
else:
print("--- error ---",end="\t")
print(start-end)
总结:好多坑没有踩过就不会有经验,这就是为什么要多码多思考了,还需要一直提升一直充电。不总结,就不会有什么沉淀;不提升,就不会用更高级的方法去建模,去看待这个魔幻的世界。