题目描述:The string "PAYPALISHIRING" is written in a zigzag( Z字形的)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);
如果有看不懂的或者对代码有指教的可以留言探讨一下。
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".
PS:解释一下什么是zigzag( Z字形的)pattern,它从左往右是由一个个可重复的矩形单元构成的,每个矩形高是rows,宽是rows-2,
字母在每个矩形中构成的规则是,先从上到下排最左边一列,然后再从左下到右上排斜对角线,
例如:qwerqwerqwer row=4
q e
w wr r
eq q e
r w
public class ZigZag_Conversion {
public static void convert(String str,int row)
{
char array[]=str.toCharArray();
if(array.length>=row)
{
//得到一共有几列
//count代表有几条高
int count=0;
for(int k=0;k<array.length;k+=(2*row-2))
{
count++;
}
//如果最后一个高后面剩余的数无法组成下一个高,则要将后面的几行都加上
int mid=count;
int shengyu=array.length-mid*row-(mid-1)*(row-2);
if(shengyu>0)
{
count+=shengyu;
}
count+=(mid-1)*(row-2);
//一行一行输出
for(int i=0;i<row;i++)
{
String rowstr="";
//标记表示矩形长的那一行
int times=0;
//对每一行空格的记录,用于对矩形宽之间的数据提取
int spacecount=1;
int midtimes=0;
//对一行上的每列做出处理
for(int j=1;j<=count;j++)
{
if(j==times*(row-1)+1)
{
int pick=(i+times*(2*row-2));
pick=(i+times*(2*row-2));
if(pick<array.length)
{
rowstr+=array[pick];
//midtime作用是在对宽的时候的判断发挥作用
//因为times在下一句已经加一,会造成不准确
midtimes=times;
times++;
spacecount=1;
}
}
else
{
if(i+(j-(times-1)*(row-1))==row)
{
rowstr+=array[spacecount*2+i+midtimes*(2*row-2)];
}
else
{
rowstr+=" ";
spacecount++;
}
}
}
System.out.println(rowstr);
}
}
else
{
System.out.println("不足以构成一个ZiZag形状");
}
}
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String str=sc.next();
int row=sc.nextInt();
convert(str,row);
}
}
如果有看不懂的或者对代码有指教的可以留言探讨一下。