一【题目类别】
- 字符串
二【题目难度】
- 中等
三【题目编号】
- 6.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);
五【题目示例】
-
示例 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
- 示例 3:
- 输入:s = “A”, numRows = 1
- 输出:“A”
六【解题思路】
- 这个题目要总结规律
- 整个形状是倒着的“Z”字形,一个“Z”字形,从上到下占用 n u m R o w s numRows numRows个为止,从左到右占用 n u m R o w s − 2 numRows-2 numRows−2个位置,所以一个“Z”字形的周期是: t = 2 ∗ n u m R o w s − 2 t=2 * numRows - 2 t=2∗numRows−2
- 有了以上信息就可以直接通过原来的字符串构造结果字符串了
- 遍历
n
u
m
R
o
w
s
numRows
numRows行,对于同一行的字符,只有两种情况(可以画一画,很容易总结出规律):
- j ( 当 前 字 符 索 引 ) m o d t = = i ( 当 前 行 ) j(当前字符索引)mod \quad t == i(当前行) j(当前字符索引)modt==i(当前行)
- j ( 当 前 字 符 索 引 ) m o d t = = k − i ( 当 前 行 的 另 一 个 位 置 ) j(当前字符索引)mod \quad t == k-i(当前行的另一个位置) j(当前字符索引)modt==k−i(当前行的另一个位置)
- 我们只需要按照上述规律将属于同一行的字符一个一个加入结果字符串中(按照从小到大行的顺序)就可以了
- 最后返回结果即可
七【题目提示】
- 1 <= s.length <= 1000
- s 由英文字母(小写和大写)、‘,’ 和 ‘.’ 组成
- 1 <= numRows <= 1000
八【时间频度】
- 时间复杂度: O ( m n ) O(mn) O(mn),其中 m m m为行数, n n n为字符串长度
- 空间复杂度: O ( n ) O(n) O(n),其中 n n n为字符串长度
九【代码实现】
- Java语言版
package String;
/**
* @Author: IronmanJay
* @Description: 6.Z 字形变换
* @CreateTime: 2022-12-01 09:04
*/
public class p6_ZigzagConversion {
public static void main(String[] args) {
String s = "PAYPALISHIRING";
int numRows = 3;
String res = convert(s, numRows);
System.out.println("res = " + res);
}
public static String convert(String s, int numRows) {
StringBuffer sb = new StringBuffer();
int len = s.length();
if (len == 0 || numRows == 1) {
return s;
}
int t = 2 * numRows - 2;
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < len; j++) {
if (j % t == i || j % t == t - i) {
sb.append(s.charAt(j));
}
}
}
return sb.toString();
}
}
- C语言版
#include<stdio.h>
#include<stdlib.h>
char * convert(char * s, int numRows)
{
int len = strlen(s);
if (len == 0 || numRows == 1)
{
return s;
}
char* res = (char*)malloc(sizeof(int) * (len + 1));
res[len] = '\0';
int index = 0;
int t = 2 * numRows - 2;
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < len; j++)
{
if (j % t == i || j % t == t - i)
{
res[index++] = s[j];
}
}
}
return res;
}
/*主函数省略*/
十【提交结果】
-
Java语言版
-
C语言版