题目描述
将一个给定字符串 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”
解答
package com.antg;
/**
* @Description: Z 字形变换
* @Author 子兔Antg
* @Date 2021/11/15
**/
public class Code_6 {
public static void main(String[] args) {
String s = "abcde";
String convert = convert(s, 4);
System.out.println(convert);
}
public static String convert(String s, int numRows) {
if(numRows==1){
return s;
}
//思路:使用一个二维矩阵来存储变换后的字符
//1.计算二维矩阵的大小
//1.1分别计算二维矩阵的宽高
int high = numRows;
int width;
int unit = s.length()/(high+high-2);//有几个v单元
int other = s.length()%(high+high-2);//剩余
int unitWidth = unit*(high-1);
int otherWidth = 0;
if(other<=high){
otherWidth = 1;
}else{
otherWidth = 1+other-high;
}
width = unitWidth+otherWidth;
//1.2创建二维矩阵
char[][] container = new char[high][width];
//2.遍历字符串进行存储
int under = 0;//向下走的坐标
boolean underAble = true;//向下走的能力
int top = high-1;//向上走的坐标
boolean topRightAble = false;//向右上走的能力
int right = 0;//向右走的坐标
for(int i = 0;i<s.length();i++){
//向下走
if(underAble){
container[under][right] = s.charAt(i);
under++;
if(under==high){
underAble = false;
topRightAble = true;
under = 0;
}
}
//下右上走
if(topRightAble){
container[top][right] = s.charAt(i);
top--;
right++;
if(top==0){
top = high-1;
topRightAble = false;
underAble = true;
}
}
}
StringBuilder res = new StringBuilder();
//3.读取二维矩阵
for(int i = 0;i<container.length;i++){
for(int j = 0;j<container[i].length;j++){
if(container[i][j]!= '\u0000'){
res.append(container[i][j]);
}
}
}
return res.toString();
}
}