将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:
P A H N
A P L S I I G
Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。
方案并非最优,胜在易于理解
class Solution {
public:
string convert(string s, int numRows) {
if(1 == numRows)return s;
const int len = s.size();
char arr[len][len];
memset(arr,'#',len*len);
int row = 0,col = 0;
int ori = 0;
for(int i = 0;i<len;++i)
{
arr[row][col] = s[i];
if( 0 == row)
{
ori = 1;
}
else if(numRows - 1 == row)
{
ori = -1;
}
if(1 == ori)
{
row++;
}
else if(-1 == ori)
{
row--;
col++;
}
}
string str("");
for(int i = 0;i<len;++i)
{
for(int j = 0;j<len;++j)
{
if('#' != arr[i][j])
str = str +arr[i][j];
}
}
return str;
}
};