ZigZag_Conversion

题目描述: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);

                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);
	}
}

如果有看不懂的或者对代码有指教的可以留言探讨一下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值