第一遍理解错了题,以为是奇数列全是连着的,偶数列隔一个写一个数:
写出程序如下,即新建一个数组,把东西都填进去,在按照行读
class Solution
{
public:
string convert(string s, int numRows)
{
int len = s.length();
int i = 0;
int shuangL = numRows;
int danL = numRows / 2;
int res = 0;
//int reme[2] = { shuangL, danL };
//求出现在有几列,及最后一列的情况
while (len >= 0)
{
if (i % 2 == 0)
{
len -= shuangL;
i++;
if (len < 0)
{
res = len + shuangL;
}
else if (len == 0)
{
res = 0;
}
}
else
{
len -= danL;
i++;
if (len < 0)
{
res = len + danL;
}
else if (len == 0)
{
res = 0;
}
}
}
string** a=new string*[numRows];
for (int s1 = 0; s1 != numRows; s1++)
{
a[s1] = new string[i];
for (int kk = 0; kk != i; kk++)
a[s1][kk] = "";
}
int strcount = 0;
for (int m = 0; (m < i)&&(strcount!=len); m++)
{
for (int n = 0; n < numRows; n++)
{
if (m % 2 == 0)
{
a[n][m] = s[strcount];
strcount++;
}
else
{
n++;
if (n < numRows)
{
a[n][m] = s[strcount];
strcount++;
}
}
}
}
string out;
for (int n = 0; n < numRows; n++)
{
for (int m = 0; m < i; m++)
{
if (!(a[n][m]).empty())
out = out + a[n][m];
}
}
return out;
}
};
按照这样做,速度坑定不行,因为理解对了题又往进去填了在按照行读,速度太慢。如下:
class Solution
{
public:
string convert(string s, int numRows)
{
int tocol = 0;
if (numRows-1)
{
int res = s.length() % (2 * numRows-2);
if (res <= numRows)
res = 1;
else
res = res - numRows + 1;
tocol = (s.length() / (2 * numRows - 2))*(numRows - 1) + res;
}
else
{
return s;
}
string** a = new string*[numRows];
for (int s1 = 0; s1 != numRows; s1++)
{
a[s1] = new string[tocol];
for (int kk = 0; kk != tocol; kk++)
a[s1][kk] = "";
}
int len = s.length();
int currow = 0;
int curcol = 0;
int strcount = 0;
bool flag = 1;
while (len != 0)
{
if (s[strcount]==NULL)
{
break;
}
a[currow][curcol] = s[strcount];
strcount++;
len--;
if ((currow < numRows-1)&&flag)
currow++;
else
{
flag = 0;
if (currow != 0)
{
currow--;
curcol++;
}
else
{
currow = 0;
currow++;
flag = 1;
}
}
}
string out;
for (int n = 0; n < numRows; n++)
{
for (int m = 0; m < tocol; m++)
{
if (!(a[n][m]).empty())
out = out + a[n][m];
}
}
for (int s1 = 0; s1 != numRows; s1++)
{
delete[] a[s1];
}
delete[] a;
return out;
}
};
最后还是看别人写的,才知道怎么弄好点。还是找到规律比较好办把,如下:
class Solution {
public:
string convert(string s, int numRows)
{
// Start typing your C/C++ solution below
// DO NOT write int main() function
string result;
if (numRows < 2) return s;
for (int i = 0; i < numRows; ++i)
{
for (int j = i; j < s.length(); j += 2 * (numRows - 1))
{
result.push_back(s[j]);
if (i > 0 && i < numRows - 1) {
if (j + 2 * (numRows - i - 1) < s.length())
result.push_back(s[j + 2 * (numRows - i - 1)]);
}
}
}
return result;
}
};