题目:
The string "PAYPALISHIRING"
is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N A P L S I I G Y I RAnd then read line by line:
"PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)
should return
"PAHNAPLSIIGYIR"
.
class Solution {
public:
string convert(string s, int numRows) {
<span style="white-space:pre"> </span>string result;
<span style="white-space:pre"> </span>//如果行数为1或者字符串的大小小于行数,直接输出原字符串
if (numRows==1||s.size()<=numRows)
{
return s;
}
<span style="white-space:pre"> </span>/计算区块大小
int cols=s.size()/(numRows+numRows-2);
int count=0;
int loc;
int j=0;
for (int i=0;i<numRows;i++)
{
for (j=0;j<cols+1;j++)
{
<span style="white-space:pre"> </span>//每一区块内,从第 i+j*(2*numRows-2)个元素开始
loc=i+j*(2*numRows-2);
if (loc>s.size()-1)
{
continue;
}
result.append(1,s[loc]);
count++;
<span style="white-space:pre"> </span>//当行数大于等于3时,每一区块内,首末两行的元素个数为1,其余为2,做一个判断,如果是2个元素,则递增 (2*numRows-2-2*i) 个
if(i>0&&i<numRows-1)
{
loc+=(2*numRows-2-2*i);
if (loc>s.size()-1)
{
continue;
}
result.append(1,s[loc]);
count++;
}
}
}
return result;
}
};
测试时,遇到了以下错误:
1、未考虑numRows为1或者元素数少于numRows的情况,造成计算cols时除数出现0
2、未考虑只有两行时的情况,如输入为 ABC,2