Z 字形变换
题目:
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:
L C I R
E T O E S I I G
E D H N
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入: s = "LEETCODEISHIRING", numRows = 3
输出: "LCIRETOESIIGEDHN"
示例 2:
输入: s = "LEETCODEISHIRING", numRows = 4
输出: "LDREOEIIECIHNTSG"
解释:
L D R
E O E I I
E C I H N
T S G
看到这个题目我们来分析一下:
1.这个是需要一个二维数组的,因为有两个方向的变化。
2.这两个方向分别是:(1)、先向下去放字符。(2)、然后再往右上角放字符。
因此代码如下:
class Solution {
public String convert(String s, int numRows) {
int str = s.length();
if(numRows == 1){
return s;
}
char[][] nums = new char[numRows][str];
int row = 0;
int col = 0;
int index = 0;
while(index < str){
while(row < numRows && index < str){ //往下走
nums[row++][col] = s.charAt(index++);
}
row--;
while(row > 0 && index < str){ //往右上角走
nums[--row][++col] = s.charAt(index++);
}
row++;
}
StringBuffer res = new StringBuffer();
for(int i = 0;i < nums.length;i++){
for(int j = 0;j < nums[i].length;j++){
if(nums[i][j] != '\0'){ //字符以"\0"结束
res.append(nums[i][j]);
}
}
}
return res.toString();
}
}
更多精彩

