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)

总结:好多坑没有踩过就不会有经验,这就是为什么要多码多思考了,还需要一直提升一直充电。不总结,就不会有什么沉淀;不提升,就不会用更高级的方法去建模,去看待这个魔幻的世界。

LeetCode 6. ZigZag Conversion & 字符串的更多相关文章

  1. [leetcode]6. ZigZag Conversion字符串Z形排列

    The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...

  2. Leetcode 6 ZigZag Conversion 字符串处理

    题意:将字符串排成Z字形. PAHNAPLSIIGYIR 如果是5的话,是这样排的 P     I AP   YR H L G N  SI A    I 于是,少年少女们,自己去找规律吧 提示:每个Z ...

  3. Java [leetcode 6] ZigZag Conversion

    问题描述: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows ...

  4. Leetcode 6. ZigZag Conversion(找规律,水题)

    6. ZigZag Conversion Medium The string "PAYPALISHIRING" is written in a zigzag pattern on ...

  5. [LeetCode] 6. ZigZag Conversion 之字型转换字符串

    The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...

  6. 蜗牛慢慢爬 LeetCode 6. ZigZag Conversion [Difficulty: Medium]

    题目 The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows li ...

  7. LeetCode 6 ZigZag Conversion 模拟 难度:0

    https://leetcode.com/problems/zigzag-conversion/ The string "PAYPALISHIRING" is written in ...

  8. leetcode 6. ZigZag Conversion

    https://leetcode.com/problems/zigzag-conversion/ 题目: 将字符串转化成zigzag模式. 例如 "abcdefghijkmlnpq" ...

  9. LeetCode 6 ZigZag Conversion(规律)

    题目来源:https://leetcode.com/problems/zigzag-conversion/ The string "PAYPALISHIRING" is writt ...

随机推荐

  1. 【转】 Ubuntu在启动器添加程序快捷方式

     转自: http://blog.csdn.net/walker0411/article/details/51555821 目录(?)[-] Ubuntu在启动器添加程序 eclipse快捷方式的创建 ...

  2. App音频内录 录音

    1.android模拟器 天天模拟器+BlueStacks 2.高清内录软件 Audio Record Wizard.exe 3.音频剪切软件 Adobe Audition CS6

  3. 需要序列化的类中没有写serialVersionUID的解决办法

    由于没赋值serialVersionUID 只是警告,不是错误,造成先前没留意设定serialVersionUID,网络两端上线运行一段时间也感觉正常.如果再增减修改field,没赋值好serialV ...

  4. 数据科学VS机器学习

    数据科学是一个范围很广的学科.机器学习和统计学都是数据科学的一部分.机器学习中的学习一词表示算法依赖于一些数据(被用作训练集)来调整模型或算法的参数.这包含了许多的技术,比如回归.朴素贝叶斯或监督聚类 ...

  5. Vivado约束文件(XDC)的探究(2)

    Vivado约束文件(XDC)的探究(2)

  6. sql 数据类型转换

    1.convert(float,endtimepart)——conver(数据类型,字段名称) 2.cast(endtimepart as float)——cast(字段名称 as 数据类型)

  7. 使用R语言-计算均值,方差等

    R语言对于数值计算很方便,最近用到了计算方差,标准差的功能,特记录. 数据准备 height <- c(6.00, 5.92, 5.58, 5.92) 1 计算均值 mean(height) [ ...

  8. [转][CentOS]修改IP后立即生效

    来自:http://bbs.51cto.com/thread-789908-1.html Linux系统里修改IP地址后该如何使之即刻生效,有两种方法可以解决: (1) sudo ifdown eth ...

  9. grafana 指标视图嵌入到其他html网页

    我们开发了一套管理平台用来监控整个系统环境的运行情况,但是在指标信息这块不想重新开发,而想直接拿grafana来用,刚开始的时候我们的管理平台和grafana是完全独立的,只能从我们平台跳转到graf ...

  10. [UE4]封装蓝图函数Print String

    World Context Object一定要赋值才会在多人游戏中出现Server和Client,如下图所示: