1 ,思路
首先生成一个二维矩阵,然后按照规则,也就是先从上到下,然后斜向上。
然后遍历完字符串之后,将其按照先行后列读出即可。
2 代码
class Solution {
public:
string convert(string s, int numRows) {
int n = s.size();
if(numRows == 1){
return s;
}
int t = numRows*2 - 2;
int col = ceil(n*1.0/t) * (numRows-1);
char map_t[numRows][col] = {0} ;
for(int i = 0; i < numRows; i++){
for(int j = 0; j < col; j++){
map_t[i][j] = 0;
}
}
int i = 0;
int rx = 0;
int rj = 0;
while(i < n){
while(i < n && rx < numRows){
map_t[rx][rj] = s[i];
rx++;
i++;
}
//斜向上
rx = rx -2;
rj ++;
while(i < n && rx > 0){
map_t[rx][rj] = s[i];
rx--;
rj++;
i++;
}
}
string res = "";
for(int i = 0;i < numRows; i++){
for(int j = 0; j < col; j++){
if(map_t[i][j] != 0){
res += map_t[i][j];
}
}
}
return res;
}
};

本文介绍了一种将字符串以Z形路径写入矩阵再按行读取的算法实现。通过生成二维矩阵,按照先垂直向下再斜向上的规则填充字符串,并最终按先行后列的方式读取形成新的字符串。
1747

被折叠的 条评论
为什么被折叠?



