题目:
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".
分析:
题目要求对一个字符串按给定的行数呈‘Z’形排列,
0 6
1 5 7
2 4 8
3 9
仔细研究发现,每2*numRows - 2个字符是一组,即
0
1 5
2 4
3
是一组,其实本题考查的是对mod的运用,看出这一点就不难找出规律了
代码:
public String convert(String s, int numRows) {
StringBuilder res = new StringBuilder();
int len = s.length();
if(len == 0 || numRows == 1)
return s;
int group = 2 * numRows - 2;
int col ;
if(len % group <= numRows - 1)
col = (len / group) * (numRows - 1) + 1;
else
col = (len / group) * (numRows - 1) + len % group + 1 - numRows;
char [][] tmp = new char[numRows][col];
for(int i = 0;i < numRows;i++)
for(int j = 0;j<col;j++)
tmp[i][j] = '/';
for(int i = 0;i < len;i++)
{
int tmp_row,tmp_col;
if(i % group <= numRows - 1)
{
tmp_row = i % group;
tmp_col = (i / group) * (numRows - 1);
}
else
{
tmp_row = group - i % group;
tmp_col = ((i % group) - numRows + 1) + (i / group) * (numRows - 1);
}
tmp[tmp_row][tmp_col] = s.charAt(i);
}
for(int i = 0 ;i < numRows;i++)
for(int j = 0;j < col;j++)
if(tmp[i][j] != '/')
res.append(tmp[i][j]);
return res.toString();
}