ZigZag Conversion

225 篇文章 0 订阅
50 篇文章 0 订阅

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" .

三行:                        四行:


之字形排列的一道题,这道题自己想了一个方法发现对最后一个散组的处理比较麻烦。参考了网上的算法,实现了一个简便的算法。

这道题是一道找规律的题。如上面的例子: 首行跟尾行的规律比较好找。相邻两个相差 2*nRow - 2。 而在剩余行,同一行相邻元素也是有规则的。nRow = 3 时, 第二行中  3跟1之间差: 2*nRow -2 - 2;nRow = 4 时, 第二行中 5 跟1之间差2*nRow -2 -2, 第三行中 4跟2 之间差2 *nRow-2 -4。依次类推。规则找到了,在非首行跟尾行,除了周期固定有一个数,中间还有一个数字,并且规律跟当前行数有关系。若当前行为i,那么相邻元素的位置为  2*nRows-2 - 2*i 。 

补充:


代码如下:

public String convert(String s, int nRows){
		int len = s.length();
		if(len==0 || nRows <2 ) return s;
		String res = "";
		int lag = 2*nRows-2;
		
		//循环行数这么多就好
		for(int i=0;i<nRows;i++){
			for(int j = i;j<len;j+=lag){
				
				res += s.charAt(j);
				//非首行跟尾行 中间要加一个
				if(i>0 && i < nRows -1){
					int temp = j+ lag-2*i;
					//从当前位置j 位置起后面 2*nRow-2-2*i 还有一个数字
                    //注意如果没有一个满的周期会报出数组越界
					
					if(temp <len)
					res += s.charAt(temp);					
				}
				
			}
		}
		return res;
		
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值