Leetcode_06题目
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:
P A H N
A P L S I I G
Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。
以下为示例:
Example 1
输入:s = "PAYPALISHIRING", numRows = 3
输出:"PAHNAPLSIIGYIR"
Example 2
输入:s = "PAYPALISHIRING", numRows = 4
输出:"PINALSIGYAHRPI"
解释:
P I N
A L S I G
Y A H R
P I
Example 3
输入:s = "A", numRows = 1
输出:"A"
个人解答及思路
char * convert(char * s, int numRows){
int s_len = strlen(s);
char *string = (char *)malloc(sizeof(char)*(s_len+1));
int loop = 2*numRows-2;
if (numRows > 1){
int i = 0;
while (i*loop<s_len){
string[i] = s[i*loop];
i++;
}
for (int row=1; row<numRows-1; row++){
int index = 0;
while (index*(loop)+row < s_len){
string[i] = s[index*(loop)+row];
i++;
if ((index+1)*(loop)-row < s_len){
string[i] = s[(index+1)*(loop)-row];
i++;
}
index++;
}
}
int index = 0;
while (index*(loop)+numRows-1 < s_len){
string[i] = s[index*(loop)+numRows-1];
i++;
index++;
}
string[i] = '\0';
}
else{
int i=0;
for (; i<s_len; i++)
string[i] = s[i];
string[i] = '\0';
}
return string;
}
思路
对于本题,考虑到需要将所有的字母按照从上到下,从左到右的字符串排列。可以采用新建
矩阵将所需字母填进矩阵,然后将未填进的矩阵格子用一个标识字符赋为矩阵元素,然后遍历矩
阵的所有格子,将非标识符的元素进行字符串连接,得到最终的字符串。
此处换了一种方法,根据索引和矩阵排列形式,将排列矩阵分为三类:第一类为第一行,第
三类为最后一行,第二类为剩下所有行。用矩阵将原字符串排列出来,然后再根据矩阵行列找到
与原字符串索引匹配的式子,两者结合可直接实现字符串的生成。
题目总结
本题对于这种想法,可能并不是最优解,从理解上来看,用矩阵直接输出的算法比较好写,所以仅供参考。如果有错,麻烦各位指正。