将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:
P A H N
A P L S I I G
Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"。
请你实现这个将字符串进行指定行数变换的函数:题目链接
示例 1:
输入:s = "PAYPALISHIRING", numRows = 3
输出:"PAHNAPLSIIGYIR"
示例 2:
输入:s = "PAYPALISHIRING", numRows = 4
输出:"PINALSIGYAHRPI"
解释:
P I N
A L S I G
Y A H R
P I
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/zigzag-conversion
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
示例 3:
输入:s = "A", numRows = 1
输出:"A"
解答
1、先计算最多会产生多少列: (s.length() / (2 * numRows - 2) + 1) * (numRows-1)
2、准备numRows * numCols 的格子,开始填这个矩阵,从左上角开始
3、dir为方向:dir为-1时,走势向下,当dir为1时候,走势向上
4、在向下走的过程中,每次列号不变,行号+1,直到最后一行改变方向,且列号+1,行号-1
5、在向上走的过程中每次,列号+1,行号-1,直到第一行改变方向,且列号不变,行号+1
6、整个矩阵填写完了,将其组装为一个字符串,将空格过滤掉。
Java 代码:
class Solution {
public String convert(String s, int numRows) {
if(numRows==1){
return s;
}
int ncol = (s.length() / (2 * numRows - 2) + 1) * (numRows-1);
char[][] grid = new char[numRows][ncol];
int i =0;
int j =0;
int idx = 0;
int dir = -1;
while(idx<s.length()){
grid[i][j] = s.charAt(idx);
if(dir==-1){
j = i == numRows-1 ? j+1 : j;
dir = i == numRows-1 ? -dir : dir;
i = i == numRows-1 ? i-1 : i+1;
}else {
j = i == 0 ? j : j + 1;
dir = i ==0 ? -dir : dir;
i = i == 0 ? i + 1 : i-1;
}
idx ++;
}
String res = "";
for(int ix=0; ix<numRows; ix++){
for(int jy=0; jy<ncol; jy++){
if(grid[ix][jy]!='\u0000'&&String.valueOf(grid[ix][jy])!=""){
res += String.valueOf(grid[ix][jy]);
}
}
}
return res;
}
}
Python 代码
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
ncol = (len(s) // (2 * numRows - 2) + 1) * (numRows - 1)
grid = [[0 for _ in range(ncol)] for _ in range(numRows)]
i = 0
j = 0
idx = 0
dir = -1
while idx < len(s):
grid[i][j] = s[idx]
if dir == -1:
j = j + 1 if i == numRows - 1 else j
dir = -dir if i == numRows - 1 else dir
i = i - 1 if i == numRows - 1 else i + 1
else:
j = j if i == 0 else j + 1
dir = -dir if i == 0 else dir
i = i + 1 if i == 0 else i - 1
idx += 1
res = ""
for g in grid:
res += ''.join([i for i in g if i!=0])
return res