leetcode每日一题
程序员文章站
2022-07-12 23:40:57
...
问题:ZigZag Conversion
思路:我尝试建立一个网格,将字符串的每个字符按zigzag这样的顺序填入网格节点,然后按照从左到右、从上到下的顺序将字符组成一个新的字符串。使用python3编写
代码:
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
s1 = ''
a = 0
n = int(len(s))
arr = [['']*n for i in range(numRows)]
if numRows == 1:
return s
while s:
for i in range(numRows):
if not s:
break
arr[i][a] = s[0]
s = s[1:]
for j in range(1, numRows-1):
if not s:
break
arr[numRows-j-1][j+a] = s[0]
s = s[1:]
a = a + numRows - 1
for i in range(numRows):
for j in range(n):
if not arr[i][j]:
continue
s1 = s1 + arr[i][j]
return s1