Z 字形变换
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。 比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下: P A H N A P L S I I G Y I R 之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。 请你实现这个将字符串进行指定行数变换的函数: string convert(string s, int numRows); 来源:力扣(LeetCode)
AC代码class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
temp = ['' for i in range(numRows)]
length = len(s)
res = ''
for i in range(numRows):
if i == 0:
j = 0
while j * numRows - j = len(s):
return s
mat = [[] for _ in range(r)]
t, x = r * 2 - 2, 0
for i, ch in enumerate(s):
mat[x].append(ch)
x += 1 if i % t
关注
打赏
热门博文
- 【Leetcode】剑指Offer 34:二叉树中和为某一值的路径
- 【Leetcode】剑指Offer 33:二叉搜索树的后序遍历序列
- 【Leetcode】剑指Offer 32-III: 从上到下打印二叉树 III
- 【Leetcode】剑指Offer 32-II: 从上到下打印二叉树 II
- 【Leetcode】剑指Offer 32-I:从上到下打印二叉树
- 【Leetcode】剑指Offer 31:栈的压入、弹出序列
- 【Leetcode】剑指Offer 30:包含min函数的栈
- 【Leetcode】剑指Offer 29:顺时针打印矩阵
- 【Leetcode】剑指Offer 28:对称的二叉树
- 【Leetcode】剑指Offer 27:二叉树的镜像