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. win10:如何开启自带虚拟机

    1.首先要找到控制面板,我们点开windows键,然后选择在所有应用中找到“Windows 系统”,打开之后,我们找到“控制面板”,打开.     2.打开控制面板之后,我们选择程序,如图示.   3 ...

  2. CodeReview常见代码问题

    路线图 常见代码问题空值未捕获潜在的异常低性能影响范围过大单测问题与原有业务逻辑不兼容缺乏必要日志错误码不符合规范参数检测缺乏或不足引用错误细节错误多重条件文不符实跨语言或跨系统交互可维护性问题硬编码 ...

  3. 【java】数据类型

    逻辑型boolean: boolean类型数据只能取值True或False,不可以0或者非0替代True或False,这点与c语言不同. 字符型char: 一个char类型的字符占两个字节.一个汉字也 ...

  4. 服务器病了吗? Linux 服务器的那些性能参数指标

    一个基于 Linux 操作系统的服务器运行的同时,也会表征出各种各样参数信息.通常来说运维人员.系统管理员会对这些数据会极为敏感,但是这些参数对于开发者来说也十分重要,尤其当你的程序非正常工作的时候, ...

  5. 协程与多路io复用epool关系

    linux上其实底层都基于libevent.so模块实现的,所以本质一样 gevent更关注于io和其它 epool只是遇到io就切换,而gevent其它等待也切换

  6. 代码编辑器之sublime text

    http://www.iplaysoft.com/sublimetext.html 1.特点: 中文乱码问题:另外,很多朋友反映表示打开中文会有乱码,其实是因为ST2本身只支持UTF-8编码,而我们常 ...

  7. xe5 android 手机上使用sqlite [转]

    在android手机上怎样使用sqlite数据库,这里用Navigator实现 增删改查. 1.新建firemonkey mobile application 2.选择blank applicatio ...

  8. Weka训练模型的存取

    因为WEKA中所有分类器都实现了Serializable,所以只需要用java的ObjectOutputStream就可以实现了. /** * 存储model * * @param model * 训 ...

  9. 关于JFame 屏幕居中显示的问题

    场景:    在利用 JAVA  的 Swing 开发 C/S 架构 的前端界面 目的:    想让 JFrame 居中显示在整个 屏幕的正中位置 方法一:JFrame frame = new JFr ...

  10. 阿里云kubernetes遭入侵pubg进程占用cpu资源100%解决方法

    发现服务器CPU占用100%,通过top命令发现pubg -c config.json -t 2占用CPU资源,kill进程会自动启动.黑客入侵方式是kubernetes创建pod. Name: ku ...