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"
.
code 如下:
#include <iostream>
#include <string>
class Solution {
public:
string convert(string s, int numRows) {
if(s.size() == 0)
return "";
if(numRows == 1)
return s;
string result(s);
int i = 0;
int j = 0;
int r_index = 0;
while(i < numRows)
{
int s_index = 0;
if(i == 0 || i == numRows - 1)
s_index = i + j*(2*numRows - 2);
else
s_index = i + j%2 *(2*(numRows-i)-2) + (j/2)*(2*numRows - 2);
if(s_index > s.size()-1)
{
i++;//another line
j = 0;//clear j.
}
else
{
result[r_index] = s[s_index];
j++;
r_index++;
}
}
return result;
}
};