题目
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"
.分析
此题是一道较为简单的字符串题,将一个字符串按照倒“之”字形写出来,要求输出其一行一行读该字符串的结果。将第一行和最后一行作为一类,中间的行作为一类,通过循环处理即可得答案。
C++代码
class Solution {
public:
string convert(string s, int numRows) {
string r = "";
int n = s.size(), m = 2*numRows-2;
if (!m) return s;
for (int i = 0;i*m < n;i++)
r += s[i*m];
for (int i = 1;i < numRows - 1;i++)
{
for (int j = 0;j*m+i < n;j++)
{
r += s[j*m+i];
if ((j+1)*m-i < n)
r += s[(j+1)*m-i];
}
}
for (int i = 0;i*m + numRows - 1 < n;i++)
r += s[i*m + numRows - 1];
return r;
}
};