自己的方法有点像题解方法2但是比他复杂很多,题解方法1的变化方向的思想很巧妙
#include<iostream>
#include<string>
#include<vector>
using namespace std;
//很蠢的二维数组做法,击败了15%的人
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1)
{
return s;
}
int n = 2*numRows-2 ;//n为每组数目
int m = s.size();
int left = m % n;
int columns;//列
if (left == 0)
{
columns=(numRows-1)*( m / n );
}
else
{
if(left<numRows)
{
columns = (numRows - 1) * (m / n)+1;
}
else
{
columns = (numRows - 1) * (m / n) + 1 + left - numRows;
}
}
char** a = new char*[numRows];//二维char数组的创建
for (int i = 0; i < numRows; i++)
{
a[i] = new char[columns];
for (int j = 0; j < columns; j++)
{
a[i][j] = ' ';
}
}
int index = 0;
for (int i = 0; i < columns; i++)
{
if (i % (numRows-1) == 0 )//正常列
{
for (int j = 0; j < numRows && index < s.size(); j++)
{
a[j][i] = s[index];
index++;
}
}
else if(index<s.size())
{
int r = i % (numRows - 1);
a[numRows-1-r][i] = s[index];
index++;
}
}
/*for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < columns; j++)
{
cout << a[i][j];
}
cout << endl;
}*/
string l="";
int index1 = 0;
for (int i = 0 ; i < numRows; i++)
{
for (int j = 0; j < columns; j++)
{
if (a[i][j] != ' ')
{
l+= a[i][j];
}
}
}
return l;
}
};
//题解方法1
class Solution1 {
public:
string convert(string s, int numRows) {
if (numRows == 1)return s;
vector<string>rows(min(numRows, int(s.size())));
int curRow = 0;
bool goingDown = false;
for (char c : s)//C++中的遍历字符串
{
rows[curRow] += c;
if (curRow == 0 || curRow == numRows - 1)
{
goingDown = !goingDown;//移动到最上面或最下面的行的时候,当前方向会发生改变
}
curRow += goingDown ? 1 : -1;//? :优先级更高,向上行数加1,向下行数-1
}
string ret; //作为返回值的字符串
for (string row : rows)ret += row;//一行一行的输出
return ret;
}
};
int main()
{
Solution1 test;
string s = "PAHNAPLSIIGYIR";
int numRows = 4;
string l = test.convert(s, numRows);
for (int i = 0; i < l.size(); i++)
{
cout << l[i];
}
}