题目:
ZigZag Conversion
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 text, int nRows);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.
Solution:
思路,先上下排列,再进行斜对角排列。
上下排列时,需插值numRows次。
斜对角排列时,需插值numRows次(插完立即回复到上下排列)
string convert(string s, int numRows)
{
int step_first = numRows;//上下循环次数
int step_second = numRows-2;//斜对角循环次数
int n = s.size();
int i =0;
int j=0;
string* str = new string[numRows];
while(i<n)
{
for(j = 0;j<step_first && i<n;j++,i++)
str[j] += s[i];
for(j = step_second;j>0 && i <n;j--,i++)
str[j] += s[i];
}
string result = "";
for(j=0;j<numRows;j++)
result += str[j];
delete[]str;
return result;
}