class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
ss = ''
if numRows == 1:
return s
for i in range(0, numRows):
for j, x in enumerate(s):
t = j % (2 * numRows - 2)
if t == i or t == 2 * numRows - 2 - i:
ss = ss + x
return ss
if __name__ == '__main__':
a = Solution()
print(a.convert('PAYPALISHIRING', 4))

找规律即可的题目,只需要注意下标从0开始算即可。
但是别人的时间复杂度都是妖怪吗,我这是O(n)了诶。
看到这篇题解,flag用得很妖孽。
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows < 2: return s
res = ["" for _ in range(numRows)]
i, flag = 0, -1
for c in s:
res[i] += c
if i == 0 or i == numRows - 1: flag = -flag
i += flag
return "".join(res)
作者:Krahets
链接:https://leetcode.cn/problems/zigzag-conversion/solutions/21610/zzi-xing-bian-huan-by-jyd/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
8789

被折叠的 条评论
为什么被折叠?



