6. Z 字形变换题解
题目来源:6. Z 字形变换
2022.03.01每日一题
每日一题专栏地址:LeetCode 每日一题题解更新中❤️💕
法一:模拟法
我们可以通过模拟的方式来进行求解
在模拟的过程之中,我们会发现他是一个有规律的排序进行
首先会先向下排列 numRows
个,然后向右上排列 numRows - 2
个,所以一个循环周期是 2*numsRows - 2
所以我们可以通过这个循环周期来判断需要多少列的数组,同时还可以通过这个的余数
来判断是否需要换行
具体代码以及注释如下:
class Solution {
public:
string convert(string s, int numRows) {
// 取得字符串的长度
int len = s.size();
// 如果 numRows 为 1或者大于等于字符串的长度
// 那么结果与愿字符串相等,直接返回就行
if (numRows == 1 || numRows >= len)
return s;
// 判断列数
int c = ceil(len * 1.0 / (2 * numRows - 2)) * (numRows - 1);
// 创建对应的统计数组
vector<vector<char>> cnt = vector(numRows, vector<char>(c, ' '));
// 开始进行模拟
int i = 0, j = 0;
// 遍历数组
for (int index = 0; index < len; index++) {
// 将字符串 s 的值,赋到对应的值
cnt[i][j] = s[index];
// 如果取余数的范围要比 numRows - 1 小
// 说明当前的位置在第一列的位置
if (index % (2 * numRows - 2) < numRows - 1)
i++;
// 反之在右上方对应的位置
else
i--, j++;
}
// 创建一个结果数组
string res = "";
// 使用一个遍历来统计字符串的个数,来提前结束循环
c = 0;
// 遍历数组
// 将对应字符添加到 res 尾部
for (auto &cc: cnt) {
for (auto ch: cc) {
if (ch == ' ')
continue;
res += ch;
c++;
if (c == len)
break;
}
}
return res;
}
};
class Solution {
public String convert(String s, int numRows) {
// 取得字符串的长度
int len = s.length();
// 如果 numRows 为 1或者大于等于字符串的长度
// 那么结果与愿字符串相等,直接返回就行
if (numRows == 1 || numRows >= len) return s;
// 判断列数
int c = (int) Math.ceil(len * 1.0 / (2 * numRows - 2)) * (numRows - 1);
// 创建对应的统计数组
char[][] cnt = new char[numRows][c];
// 开始进行模拟
int i = 0, j = 0;
// 遍历数组
for (int index = 0; index < len; index++) {
// 将字符串 s 的值,赋到对应的值
cnt[i][j] = s.charAt(index);
// 如果取余数的范围要比 numRows - 1 小
// 说明当前的位置在第一列的位置
if (index % (2 * numRows - 2) < numRows - 1) i++;
// 反之在右上方对应的位置
else {
i--;
j++;
}
}
// 创建一个结果数组
String res = "";
// 使用一个遍历来统计字符串的个数,来提前结束循环
c = 0;
// 遍历数组
// 将对应字符添加到 res 尾部
for (char[] cc : cnt) {
for (char ch : cc) {
if (ch == '\u0000') continue;
res += ch;
c++;
if (c == len) break;
}
}
return res;
}
};