Problem
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 R
And 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 s, int numRows);
Code
class Solution {
public:
string convert(string s, int numRows) {
string result;
if(numRows <= 1 || s.length() == 0)
return s;
if(numRows == 2){
for (int i = 0; i < s.length(); i = i + 2) {
result.append(1,s[i]);
}
for (int j = 1; j < s.length(); j = j + 2) {
result.append(1,s[j]);
}
return result;
}
int len = s.length();
int max = 2 * numRows - 2;//定义最大间隔
int change = max;//初始化change,在循环中change是可能被改变的
for (int i = 0; i < numRows; i++)
{
if(i == 0)
{//处理第一行的情况
for (int j = 0; j < len; j = j + max) {
result.append(1,s[j]);
}
}
else if (i == numRows - 1)//处理最后一行的情况
{
for (int j = numRows - 1; j < len; j = j + max) {
result.append(1,s[j]);
}
}
else{//处理其他行的情况
change = change - 2;
for (int j = i; j < len;j = j + max) {
result.append(1,s[j]);
if(j + change < len)
result.append(1,s[j + change]);
}
}
}
return result;
}
};