6. Z 字形变换
①题目描述
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 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);
②示例
输入: s = "LEETCODEISHIRING", numRows = 3
输出: "LCIRETOESIIGEDHN"
输入: s = "LEETCODEISHIRING", numRows = 4
输出: "LDREOEIIECIHNTSG"
解释:
L D R
E O E I I
E C I H N
T S G
③解法
方法一:逐字节读取字符串
假设原字符串为“abcdefghijk”
,摆成4行。
我们引入一个数组arr,数组大小为4,接着遍历字符串,设i为字符串的下标:
i = 0时,arr[0] = "a";
i = 1时,arr[1] = "b";
i = 2时,arr[2] = "c";
i = 3时,arr[3] = "d";
i = 4时,arr[2] = "ce";
i = 5时,arr[1] = "bf";
……
i = 10时,arr[2] = "ceik";
接着逐行读入arr数组即可得到答案。
源程序:
class Solution {
public:
string convert(string s, int numRows) {
if(numRows == 1)
return s;
int s_length = s.length();
int row = 0, flag = 0;
string arr[numRows];
for(int i = 0; i < s_length; i++) {
arr[row] += s[i];
if(flag == 0) {
if(row + 1 >= numRows)
row--, flag = 1;
else
row++;
}
else {
if(row - 1 < 0)
row++, flag = 0;
else
row--;
}
}
string new_s = "";
for(int i = 0; i < numRows; i++) {
new_s += arr[i];
}
return new_s;
}
};
Leetcode的测试结果:
方法二:逐行读入法
假设原字符串为“abcdefghijk”,摆成4行。
思路:首先访问 行 0
中的所有字符,接着访问 行 1
,然后 行 2
,依此类推…:
设z字返回第一行前所有的数字为一组,该组数字数目为g_length = 2 * numRows -2
;
行0、行numRows - 1:下标为i + g_length * t(t = 0,1,2...)
中间行:下标为i + g_length * t(t = 0,1,2...)和下标为i + g_length * t - 2 * i(t = 1,2...)
class Solution {
public:
string convert(string s, int numRows) {
if(numRows == 1)
return s;
int s_length = s.length();
int g_length = 2 * numRows - 2;
string result = "";
for(int i = 0; i < numRows; i++) {
int j = i;
while(j < s_length) {
result += s[j];
j += g_length;
//cout<<"i: "<<i<<" j + g_length - i:"<<j + g_length - i<<" s_length:"<<s_length<<endl;
if(i > 0 && i < numRows - 1 && j - i * 2 < s_length) {
//cout<<" "<<endl;
result += s[j - i * 2];
}
}
//cout<<result<<endl;
}
return result;
}
};
Leetcode的测试结果:
④总结
题目相对挺简单的,继续coding!